finding text files in C# console applications

BobLewiston

In Runtime
Messages
182
In C# console applications, isn't there a simpler way than handling exceptions to just find out if a text file of a given name exists in the current directory? I'm talking about something along the same lines as the following methods:

create text file:
Code:
StreamWriter SW = File.CreateText ("MyFile.txt");
open existing text file:
Code:
StreamReader SR = File.OpenText ("MyFile.txt");
append to text file:
Code:
StreamWriter SW  = File.AppendText ("MyFile.txt");
 
I would just check if the file exists before setting up the StreamReader etc. The .Net framework provides a means for you to do this.

Code:
string fileName = "MyFile.txt"; // The path of the file

if (File.Exists(fileName)) // If the file exists
{

// Shizzle

}
else
{
Console.Writeline("Oh cock.");
}

Hope that helps, unless I misunderstood you.

http://msdn.microsoft.com/en-us/library/system.io.file.exists.aspx
 
You have to ensure the file exists and the file is accessible to your program.

Write a [reusable] function that attempts to open the file for reading and uses a try-catch block. Have it return a bool. Use this function to test if the file can be opened before you attempt to open it for actual reading. This way, you only have to write the try-catch block once, namely when you write the function. I do C++ not C#, but maybe that'll help?

I would also learn about all the methods dealing with opening files in C#. There are probably lots of member functions for the objects dealing with this.
 
Back
Top Bottom