user278618
user278618

Reputation: 20262

Problem with access to file

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.

Upvotes: 1

Views: 1479

Answers (4)

Hans Passant
Hans Passant

Reputation: 942267

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"));

Upvotes: 1

Jesse C. Slicer
Jesse C. Slicer

Reputation: 20157

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.

Upvotes: 0

Austin Salonen
Austin Salonen

Reputation: 50235

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.

Upvotes: 0

Chris Taylor
Chris Taylor

Reputation: 53729

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.

Upvotes: 1

Related Questions