Trying to create a string from a file

Currently trying to create a string from a text file, however, it appears to be a bug that prevents the stream reader from reading the text file.

    private string testString = "Cheese";
    private void openToolStripMenuItem_Click(object sender, EventArgs e)
    {
        if (openFileDialog.ShowDialog() != DialogResult.Cancel)
        {
            fileName = openFileDialog.FileName;
            LoadFile();
        }
    }

    private void LoadFile()
    {
        String lineFromFile = "Chicken";
       *StringBuilder RawFileInput = new StringBuilder();
        using (StreamReader reader = new StreamReader(fileName))
        {

            while ((lineFromFile = reader.ReadLine()) != null)
            {
                RawFileInput.AppendLine(lineFromFile);
            }
        }*
        testString = lineFromFile; 
        testTB.Text = testString;

    }

      

The output code must have an output code that must be empty, but if the code code between the asterisks is commented out, the test phrase Chicken will be displayed in the output text box. So I'm pretty sure there is a problem with this particular block, however I can't figure out what. Thanks in advance.

+3


source to share


3 answers


If I understand your code correctly, you are trying to set testTB.Text with text in your file. With that in mind, there shouldn't be your last lines:

    testString = RawFileInput.ToString(); 
    testTB.Text = testString;

      



You can achieve the same result without the need for a StringBuilder by replacing your entire LoadFile method with this line:

testTB.Text = File.ReadAllText(fileName);

      

+1


source


You should be able to read the entire document, for example:

var builder = new StringBuilder();
using(var reader = new StreamReader(path))
     builder.Append(reader.ReadToEnd());

      



This would be ideal as it is more revealing than ReadAllText

.

ReadToEnd works best when you need to read all data from the current position to the end of the stream. If you need more control over how many characters are read from the stream, use the Read (Char [], Int32, Int32) method overload, which usually results in better performance. ReadToEnd assumes that the thread knows when it has reached the end. For interactive protocols where the server only sends data when you request it and does not close the connection, ReadToEnd can block indefinitely because it does not reach the end and should be avoided.

0


source


If you want the content of the file to fill the text box, just set the Multiline property to true and use File.ReadAllLines()

testTb.Lines = File.ReadAllLines(fileName);

      

0


source







All Articles