メモ帳:
Hello world!
どのようにC#に入れて、文字列に変換しますか?
これまでのところ、私はメモ帳のパスを取得しています。
string notepad = @"c:\oasis\B1.text"; //this must be Hello world
私にアドバイスしてください..私はこれに精通していません..tnx
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);
使用するFile.ReadAllText
string text_in_file = File.ReadAllText(notepad);
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();
テキストファイルからの読み取り(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();
この例を確認してください。
// 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();