开发者

get the value of notepad and put it inside the c# string?

Notepad:

Hello world!

How I'll put it in C# and convert it into string..?

So far, I'm getting the path of the notepad.

 string notepad = @"c:\oasis\B1.text"; //this 开发者_StackOverflowmust be Hello world

Please advice me.. I'm not familiar on this.. tnx


You can read text using the File.ReadAllText() method:

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

    }


You need to read the content of the file, e.g.:

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

Or, as simply as possible:

return File.ReadAllText(path);


make use of StreamReader and read the file as shown below

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


Use File.ReadAllText

string text_in_file = File.ReadAllText(notepad);


check this example:

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


Reading From a Text File (Visual C#), in this example @ is not used when StreamReader is being called, however when you write the code in Visual Studio it will give the below error for each \

Unrecognized escape sequence

To escape this error you can write @ before " that is at the beginning of your path string. I shoul also mentioned that it does not give this error if we use \\ even if we do not write @.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜