tags:

views:

60

answers:

4

Hi,

I have winforms application and it has reference to library MyLibrary.

MyLibrary has method:

string[] GiveMeNamesOfAirports()
{
string[] lines= File.ReadLines("airports.txt");
foreach(string line in lines)
...
}

And when I run my Winforms application:

I get error:

file couldn't be find.

I was trying other function:

string[] lines = File.ReadAllLines(Path.Combine(System.Environment.CurrentDirectory, "airports.txt"));

string[]  lines = File.ReadAllLines(Path.Combine(Assembly.GetExecutingAssembly().Location, "airports.txt")); 
string[] lines = File.ReadAllLines(Path.Combine(Assembly.GetAssembly(typeof(Airport)).Location, "airports.txt"));

File is in project MyLibrary ( I see it in solution, and it is in folder of MyLibrary.

I set Copy to ouptput directory to Copy always, and Build Action to Content.

+1  A: 

For System.Environment.CurrentDirectory to work you will need to have the "airports.txt" file in the bin\release or bin\debug (depending on what buid you are running) directory when running from within VS.

The two using the Assembly location won't work because Location includes the Assembly name, so it has more than just the path.

Chris Taylor
A: 

Does this mean MyLibrary has a file called airports.txt?

If so, you'll want to be sure the file is set to be included in the build output. Right-click on the file in Visual Studio and choose Properties. From the Properties window, there is a Copy to Output Directory property you can set to Copy Always and you should have no more problems.

Austin Salonen
A: 

Every one of your methods above is assuming the file "airports.txt" is in the same folder as your executable. Do note that by Visual Studio defaults, the debug version of your executable (which is used when debugging) is at bin\Debug and the release version you'll give to your users is at bin\Release.

Jesse C. Slicer
Technically, it assumes the file is in the current working directory. You can change this in your project settings under 'Debug'.
Ron Warholic
+1  A: 

It is unwise to use a relative path name for a file. Your program's working directory might change and will then fail to find the file. Generate the absolute path name of the file like this:

    public static string GetAbsolutePath(string filename) {
        string dir = System.IO.Path.GetDirectoryName(Application.StartupPath);
        return System.IO.Path.Combine(dir, filename);
    }

Usage:

         string[] lines= File.ReadLines(GetAbsolutePath(@"mylibrary\airports.txt"));
Hans Passant
I can't use Application.StartupPath ( i have only System.Net.Mime.MediaTypeNames.Application to choose). The method is in class library, not in winforms.
@phenevo: then use System.Reflection.Assembly.GetEntryAssembly().Location
Hans Passant
System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location),@"MyLibrary\airports.txt" works, another methods not