获取记事本的值并将其放在c#字符串中?

ghi*_*hie 5 c# notepad file

记事本:

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

Ken*_*isa 7

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


Mat*_*ott 6

您需要阅读文件的内容,例如:

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)


Pra*_*ana 5

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


SwD*_*n81 5

使用 File.ReadAllText

string text_in_file = File.ReadAllText(notepad);
Run Code Online (Sandbox Code Playgroud)