开发者

C#: new file() - where is the root save location?

开发者 https://www.devze.com 2023-01-08 13:19 出处:网络
If i make the call File myFile = new File(\'myfile.txt\'); where is does this开发者_开发技巧 get saved to?It\'s relative to the process\'s current directory. What that is will depend on how your appli

If i make the call File myFile = new File('myfile.txt'); where is does this开发者_开发技巧 get saved to?


It's relative to the process's current directory. What that is will depend on how your application has been started, and what else you've done - for example, some things like the choose file dialog can change the current working directory.

EDIT: If you're after a temporary file, Path.GetTempFileName() is probably what you're after. You can get the temp folder with Path.GetTempPath().


That won't compile.

EDIT: However, if you're after where creating a text file using StreamWriter or File.Create("text.txt"), etc, then I defer to the other answers above; where it will be where the application is running from. Be aware as others mentioned that if you're working out of debug it will be in the debug folder, etc.


NORMALLY it gets saved to the same directory the executable is running in. I've seen exceptions. (I can't remember the specifics, but it threw me for a loop. I seem to recall it being when it's run as a scheduled task, or if it's run from a shortcut.

The only reliable way to know where it is going to save if you are using the code snippet you provided is to check the value of System.Environment.CurrentDirectory. Better yet, explicitly state the path where you want it to save.

Edit - added

I know this is a bit late in modifying this question, but I found a better answer to the problem of ensuring that you always save the file to the correct location, relative to the executable. The accepted answer there is worth up-votes, and is probably relevant to your question.

See here: Should I use AppDomain.CurrentDomain.BaseDirectory or System.Environment.CurrentDirectory?

0

精彩评论

暂无评论...
验证码 换一张
取 消