получить значение блокнота и поместить его в строку c #? - PullRequest
5 голосов
/ 03 июня 2011

Блокнот:

Hello world!

Как поместить его в C # и преобразовать в строку ..?

Пока я получаю путь к блокноте.1006 *

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

Пожалуйста, посоветуйте мне .. Я не знаком с этим .. tnx

Ответы [ 6 ]

7 голосов
/ 03 июня 2011

Вы можете читать текст, используя метод 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.  
        }

    }
6 голосов
/ 03 июня 2011

Вам необходимо прочитать содержимое файла, например ::10000

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

Или как можно проще:

return File.ReadAllText(path);
5 голосов
/ 03 июня 2011

Использование File.ReadAllText

string text_in_file = File.ReadAllText(notepad);
5 голосов
/ 03 июня 2011

используйте 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 голосов
/ 03 июня 2011

проверьте этот пример:

// 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();
3 голосов
/ 03 июня 2011

Чтение из текстового файла (Visual C #) , в этом примере @ не используется при вызове StreamReader, однако, когда вы пишете код в Visual Studio, он выдаст следующееошибка для каждой \

Нераспознанная escape-последовательность

Чтобы избежать этой ошибки, вы можете написать @ перед " в начале строки вашего пути,Я также упомянул, что эта ошибка не выдается, если мы используем \\, даже если мы не пишем @.

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