-1

I'm trying to get my program to read code from a .txt and then read it back to me, but for some reason, it crashes the program when I compile. Could someone let me know what I'm doing wrong? Thanks! :)

using System;
using System.IO;

public class Hello1
{
    public static void Main()
    {   
        string    winDir=System.Environment.GetEnvironmentVariable("windir");
        StreamReader reader=new  StreamReader(winDir + "\\Name.txt");
            try {      
            do {
                        Console.WriteLine(reader.ReadLine());
            }   
            while(reader.Peek() != -1);
            }      
            catch 
            { 
            Console.WriteLine("File is empty");
            }
            finally
            {
            reader.Close();
            }

    Console.ReadLine();
    }
}
7
  • 1
    this doesn't crash on compile Commented Oct 8, 2013 at 19:27
  • 2
    I think you don't have access to windir\name.txt run program as elevated and check Commented Oct 8, 2013 at 19:28
  • Post the error message what you're getting to get help Commented Oct 8, 2013 at 19:31
  • Please consider searching for your question title first - i.e. MSDN have good basic How-to on reading file . Commented Oct 8, 2013 at 19:33
  • When executing the .exe, I get a "Program.exe has encountered a problem and needs to close" Window.
    – Nat
    Commented Oct 8, 2013 at 19:34

6 Answers 6

3

I don't like your solution for two simple reasons:

1)I don't like gotta Cath 'em all(try catch). For avoing check if the file exist using System.IO.File.Exist("YourPath")

2)Using this code you haven't dispose the streamreader. For avoing this is better use the using constructor like this: using(StreamReader sr=new StreamReader(path)){ //Your code}

Usage example:

        string path="filePath";
        if (System.IO.File.Exists(path))
            using (System.IO.StreamReader sr = new System.IO.StreamReader(path))
            {
                while (sr.Peek() > -1)
                    Console.WriteLine(sr.ReadLine());
            }
        else
            Console.WriteLine("The file not exist!");
0
3

If your file is located in the same folder as the .exe, all you need to do is StreamReader reader = new StreamReader("File.txt");

Otherwise, where File.txt is, put the full path to the file. Personally, I think it's easier if they are in the same location.

From there, it's as simple as Console.WriteLine(reader.ReadLine());

If you want to read all lines and display all at once, you could do a for loop:

for (int i = 0; i < lineAmount; i++)
{
    Console.WriteLine(reader.ReadLine());
}
0
1

Use the code below if you want the result as a string instead of an array.

File.ReadAllText(Path.Combine(winDir, "Name.txt"));
1

Why not use System.IO.File.ReadAllLines(winDir + "\Name.txt")

If all you're trying to do is display this as output in the console, you could do that pretty compactly:

private static string winDir = Environment.GetEnvironmentVariable("windir");
static void Main(string[] args)
{
    Console.Write(File.ReadAllText(Path.Combine(winDir, "Name.txt")));
    Console.Read();
}
3
  • 1
    Also, why not Path.Combine(winDir, "Name.txt") -- it's even better.
    – Jon
    Commented Oct 8, 2013 at 19:28
  • Im pretty new to C#, so I'm not sure what the best ways for file IO are yet. Could you explain how I would use this to extract a list of values into my program? Thanks :)
    – Nat
    Commented Oct 8, 2013 at 19:28
  • The method above leverages a streamreader in a Using block, so it basically does what you were trying to do without having to write it all out. It returns a string array representing the lines of the text file. Commented Oct 8, 2013 at 19:31
0
using(var fs = new FileStream(winDir + "\\Name.txt", FileMode.Open, FileAccess.Read))
{
    using(var reader = new  StreamReader(fs))
    {
        // your code
    }
}
0

The .NET framework has a variety of ways to read a text file. Each have pros and cons... lets go through two.

The first, is one that many of the other answers are recommending:

String allTxt = File.ReadAllText(Path.Combine(winDir, "Name.txt"));

This will read the entire file into a single String. It will be quick and painless. It comes with a risk though... If the file is large enough, you may run out of memory. Even if you can store the entire thing into memory, it may be large enough that you will have paging, and will make your software run quite slowly. The next option addresses this.

The second solution allows you to work with one line at a time and not load the entire file into memory:

foreach(String line in File.ReadLines(Path.Combine(winDir, "Name.txt")))
  // Do Work with the single line.
  Console.WriteLine(line);

This solution may take a little longer for files because it's going to do work MORE OFTEN with the contents of the file... however, it will prevent awkward memory errors.

I tend to go with the second solution, but only because I'm paranoid about loading huge Strings into memory.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.