记事本:
Hello world!
我该如何在C#中将其转换为字符串并放置?
到目前为止,我已经得到了记事本的路径。
string notepad = @"c:\oasis\B1.text"; //this must be Hello world
请给我建议。我对此不熟悉。谢谢。
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.
}
}
您需要读取文件的内容,例如:
using (var reader = new StreamReader(new FileStream(path, FileMode.Open, FileAccess.Read))
{
return reader.ReadToEnd();
}
return File.ReadAllText(path);
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();
StreamReader
时不使用@
,但在Visual Studio中编写代码时,对于每个\
都会出现以下错误:
为了避免这个错误,可以在路径字符串开头的无法识别的转义序列
"
之前写@
。
我还应该提到,即使我们没有写@
,如果使用\\
,也不会出现此错误。// Read the file as one string.
System.IO.StreamReader myFile = new System.IO.StreamReader(@"c:\oasis\B1.text");
string myString = myFile.ReadToEnd();
myFile.Close();
// Display the file contents.
Console.WriteLine(myString);
// Suspend the screen.
Console.ReadLine();
请查看以下示例:
// Read the file as one string.
System.IO.StreamReader myFile =
new System.IO.StreamReader("c:\\test.txt");
string myString = myFile.ReadToEnd();
myFile.Close();
// Display the file contents.
Console.WriteLine(myString);
// Suspend the screen.
Console.ReadLine();