Home > Mobile >  How to read/write a file from a relative path in C#, WPF?
How to read/write a file from a relative path in C#, WPF?

Time:12-08

It only works if I use the absolute path, but I want it relative. I tried AppDomain.CurrentDomain.BaseDirectory but it goes to the bin folder where the files are not, they are in the project folder.

What should I do?

try
{
   using StreamReader reader = new("input.txt");
   using StreamWriter writer = new("resources\\output.txt");
   string line;

   while ((line = reader.ReadLine()) != null)
   {
      writer.WriteLine(line);
   }
      reader.Close();
      writer.Close();
}
catch (FileNotFoundException)
{
   MessageBox.Show("File Not Found");
}

CodePudding user response:

They are in the project folder.

Well, you need to understand that there is no such thing as "project folder" at runtime.

You may for example develop your application on a machine with Visual Studio installed and keep the source code files in some directory. You then build the app and deploy the compiled binaries to a another machine which has no source code files or build tools.

You should copy the files that you are trying to read from and write to to the output directory of your executable for your relative paths to work.

Select the files in the Solution Explorer in Visual Studio and set their Build Action to Content, and Copy to Output Directory to Copy if newer.

  • Related