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

5

记事本:

Hello world!

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

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

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

请给我建议。我对此不熟悉。谢谢。

2
你是在问如何读取在记事本中创建的文件吗? - n8wrl
6个回答

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.  
        }

    }

这不正确,你的File.Exists调用和实际读取文件之间存在竞态条件。如果在此期间删除了文件,你的解决方案将崩溃。 - Greg D
@Greg D,你觉得这有点吹毛求疵了吗?这个问题有什么让你觉得代码需要那么牢固的吗? - Ken Pespisa
@Greg D,我再想了想,我偶然发现了你的答案,我很喜欢。谢谢!我已经更新了我的答案。(虽然我仍然不同意那个踩的人 :)) - Ken Pespisa
在这种情况下,是的,代码应该是如此牢固。特别是因为很容易做到这一点,那些挑剔的问题很容易成为您代码库中的安全漏洞。 :) - Greg D

6

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

using (var reader = new StreamReader(new FileStream(path, FileMode.Open, FileAccess.Read))
{
    return reader.ReadToEnd();
}

或者,尽可能简单地说:
return File.ReadAllText(path);

5

使用File.ReadAllText方法。

string text_in_file = File.ReadAllText(notepad);

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

3
从文本文件中读取(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();

3

请查看以下示例:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接