获取notepad的值,并将其放入c字符串中

本文关键字:字符串 notepad 的值 获取 | 更新日期: 2023-09-27 17:58:13

记事本:

Hello world!

我将如何将它放在C#中并将其转换为字符串。。?

到目前为止,我已经找到了记事本的路径。

 string notepad = @"c:'oasis'B1.text"; //this must be Hello world

请告诉我……我对此不熟悉。。tnx

获取notepad的值,并将其放入c字符串中

您可以使用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);

使用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();

使用File.ReadAllText

string text_in_file = File.ReadAllText(notepad);

检查此示例:

// 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();

从文本文件读取(Visual C#),在本例中,调用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();