C#:new file() - 根保存位置在哪里?

发布于 2024-09-10 20:30:46 字数 57 浏览 2 评论 0原文

如果我拨打 File myFile = new File('myfile.txt');它保存到哪里?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

橘和柠 2024-09-17 20:30:46

它相对于进程的当前目录。这取决于您的应用程序是如何启动的,以及您还做了什么 - 例如,选择文件对话框之类的一些操作可以更改当前工作目录。

编辑:如果您需要临时文件,< code>Path.GetTempFileName() 可能就是您想要的。您可以使用 Path 获取临时文件夹。 GetTempPath()

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().

凶凌 2024-09-17 20:30:46

那不会编译。

编辑:但是,如果您在使用 StreamWriter 或 File.Create("text.txt") 等创建文本文件之后,那么我会遵循上面的其他答案;它将是应用程序运行的位置。请注意,正如其他人提到的,如果您正在调试,它将位于调试文件夹等中。

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.

清晰传感 2024-09-17 20:30:46

通常它会保存到可执行文件运行的同一目录中。我见过例外。 (我不记得具体细节了,但这让我陷入了困境。我似乎记得它是作为计划任务运行的,或者是从快捷方式运行的。

知道它要去哪里的唯一可靠的方法如果您使用提供的代码片段,则保存是检查 System.Environment.CurrentDirectory 的值,更好的是,明确说明您希望其保存的路径

编辑 - 添加<。 /strong>

我知道修改这个问题有点晚了,但我找到了一个更好的答案来解决这个问题,即确保始终将文件保存到正确的位置,相对于可执行文件,那里接受的答案是值得的。投票,并且可能与您的问题相关,

请参阅此处:我应该使用AppDomain.CurrentDomain.BaseDirectory还是System.Environment.CurrentDirectory?

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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文