tags:

views:

254

answers:

4

I want to read a text file from my local directory, I added the text file to my c# solution, so it would get copied at deployment.. but how do i open it? I've been searching but all the examples assume I have a C:\textfile.txt:

I tried just reading the file

if (File.Exists("testfile.txt"))
{
   return true;
}

That didn't work. Then I tried:

if (File.Exists(@"\\TextConsole\testfile.txt"))
{
   return true;
}

but still wont open it.. any ideas??

A: 

you need to use one of the following after the check you have made

 string path = @"\\TextConsole\testfile.txt"";
 if (File.Exists(path))
 {
  FileStream fileStream = File.OpenRead(path); // or
  TextReader textReader = File.OpenText(path); // or
  StreamReader sreamReader = new StreamReader(path);
 }
Asad Butt
it won't find the file, because it doesn't exist in his build directory.
Stan R.
In my eyes the proper way would be `string txtPath = Path.Combine(Environment.CurrentDirectory, "testfile.txt");`.
Bobby
+2  A: 

Just because you added it to your solution doesn't mean the file get's placed into your output Build directory. If you want to use relative path, make sure your TextFile is copied during build to the output directory. To do this, in solution explorer go to properties of the text file and set Copy to Output Directory to Always or Copy if newer

Then you can use

File.Open("textfile.txt");
Stan R.
thanks a lot...
Dabiddo
A: 

If the file is indeed in c:\textfile.txt, you can find it like this:

if (File.Exists(@"c:\testfile.txt"))
{
   return true;
}

But you should use Path.Combine to build a nested file path and DriveInfo to work with drive details.

Oded
+1  A: 

You can use the first option if you copy it to your output directory

CopyToOutput

statenjason