5

メモ帳:

Hello world!

どのようにC#に入れて、文字列に変換しますか?

これまでのところ、私はメモ帳のパスを取得しています。

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

私にアドバイスしてください..私はこれに精通していません..tnx

4

6 に答える 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.  
        }

    }
于 2011-06-02T21:01:30.250 に答える
6

ファイルの内容を読む必要があります。例:

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

または、できるだけ簡単に:

return File.ReadAllText(path);
于 2011-06-02T21:02:34.313 に答える
5

使用するFile.ReadAllText

string text_in_file = File.ReadAllText(notepad);
于 2011-06-02T21:02:46.510 に答える
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();
于 2011-06-02T21:01:23.697 に答える
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();
于 2011-06-02T21:06:03.420 に答える
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();
于 2011-06-02T21:13:11.937 に答える