Home > OS >  How to create a CSV file in the same directory where I have my code instead of creating it in "
How to create a CSV file in the same directory where I have my code instead of creating it in "

Time:12-10

I want to create a .csv file in the same directory where I have my code or class but the file always end up been created in the "bin/debug/net6.0" or "bin/release/net6.0" directory.

I have tried all the following but the file is till created in "bin/debug/net6.0" and when I run the code in release mode it gets created in "bin/release/net6.0"

using (StreamWriter writer = new StreamWriter("array.csv")

string directory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
        string filePath = Path.Combine(directory, "array.csv");
        Directory.SetCurrentDirectory(directory);
        using (StreamWriter writer = new StreamWriter(filePath))
string directory = Directory.GetCurrentDirectory();
        string filePath = Path.Combine(directory, "array.csv");
        using (StreamWriter writer = new StreamWriter(filePath)}

CodePudding user response:

I think you need some basic knowledge about Visual Studio. When you start the program first it compiles it and creates an executable file. Then the executable file is started. You can set path where the executable shall be created in the project settings. There are two different pathes for the Debug and the Release build possible. By default the pathes are set to the Debug/Release directories which you mentioned. Then when your executable is started, the path where it is is this path which you query with Assembly.GetExecutingAssembly().Location. Therefore your CSV file will be in the same path where the compiler generates the executable. The general behaviour for publishing a program would be to deliver it without the source files and the program is then in an different directory of the customers. In this case the CSV file would be in that new directory too. For changing that in your case I would suggest following possibilities:

  1. quick and dirty: copy the executable files together with all additional from the compiler generated files like dll files to your source directory and start it there by the file explorer.
  2. a professional solution would look like: create a special directory for your program like customers have it. Create there a subdirectory like "data". Change your first line to

string directory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location @"\data");

Copy the executable and all other from the compiler created files to the program directory and start it there. In this case your csv file would be created in the data directory below the program directory.

  • Related