记事本:
Hello world!
Run Code Online (Sandbox Code Playgroud)
我将如何将它放入C#并将其转换为字符串..?
到目前为止,我正在寻找记事本的路径.
string notepad = @"c:\oasis\B1.text"; //this must be Hello world
Run Code Online (Sandbox Code Playgroud)
请建议我..我对此不熟悉.. tnx
您可以使用以下File.ReadAllText()方法阅读文本:
public static void Main()
{
string path = @"c:\oasis\B1.txt";
try {
// Open the file to read from.
string readText = System.IO.File.ReadAllText(path);
Console.WriteLine(readText);
}
catch (System.IO.FileNotFoundException fnfe) {
// Handle file not found.
}
}
Run Code Online (Sandbox Code Playgroud)
您需要阅读文件的内容,例如:
using (var reader = new StreamReader(new FileStream(path, FileMode.Open, FileAccess.Read))
{
return reader.ReadToEnd();
}
Run Code Online (Sandbox Code Playgroud)
或者,尽可能简单:
return File.ReadAllText(path);
Run Code Online (Sandbox Code Playgroud)
使用StreamReader并读取文件,如下所示
string notepad = @"c:\oasis\B1.text";
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader(notepad))
{
while (sr.Peek() >= 0)
{
sb.Append(sr.ReadLine());
}
}
string s = sb.ToString();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6711 次 |
| 最近记录: |