2

I want to create a file relative to Program.cs. This code in case of VSCode works correct:

string myFile1 = @".\temp1.txt";
File.Create(myFile1);
string myFile2 = "./temp2.txt";
File.Create(myFile2);

but Visual Studio IDE 2022 creates file in:

`MyProject\bin\Debug\net6.0`

Is there any universal solution?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Developer Mister
  • 572
  • 3
  • 11
  • 1
    You need to define relative. – Soleil Nov 30 '22 at 10:59
  • @Soleil what do you mean? please write a code – Developer Mister Nov 30 '22 at 11:07
  • C# is a compiled language. This means that `Program.cs` does not exist on the computer that executes this code! The location of the *source code* is completely irrelevant while executing the application. What you actually need is to find the location *of the executable*. How to do this is explained in the linked duplicate question. – Konrad Rudolph Nov 30 '22 at 13:02

1 Answers1

1

You can include the following method anywhere within your project:

using System.Runtime.CompilerServices

public static string GetSourceFilePathName( [CallerFilePath] string? callerFilePath = null )
    => callerFilePath ?? "";

Then, you can invoke that method from your Program.cs, and it will give you C:\Users\YOU\Documents\Projects\MyProject\Program.cs.

I suppose you know what to do from there.

Mike Nakis
  • 56,297
  • 11
  • 110
  • 142
  • I've found an unversal solution: `string netDirectoryPath = @$"{Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location)}"; string projectDirectoryPath = @$"{netDirectoryPath}\..\..\.."; File.Create(@$"{projectDirectoryPath}\temp.txt");` – Developer Mister Nov 30 '22 at 12:50
  • @DeveloperMister Your code is … odd, to say the least. Why are you going up *three levels*? This doesn’t look very universal at all. You write that the duplicate is not applicable here, but I still think it very much is, and that it solves your problem. – Konrad Rudolph Nov 30 '22 at 12:52