将文件复制到 tmp 文件夹的推荐方法是什么?
我需要将文件复制到临时位置才能操作它。我需要确保我始终可以复制该文件。
- 下面的代码正确吗?
- 它是否确保永远不会尝试复制到已经存在的位置?
- 有失败的可能吗? (我应该捕获任何异常吗)
我正在使用的代码如下:
string tmpFile = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
提前致谢。
I need to copy a file to a tmp location in order to manipulate it. I need to ensure that I always can copy the file.
- Is the following code correct?
- Does it ensure that never try to copy to a location that already exists?
- Is there any chance of failure? (Should I catch any exceptions)
The code that I am using is the following:
string tmpFile = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
也许使用
Path.GetTempFileName
< /a> 代替?该方法可能会抛出 IOException ,因此您应该在某个时候捕获它。确切的位置更多地取决于该代码存在的上下文。
请注意,此方法还会在磁盘上创建文件,因此不存在其他进程在此调用和代码写入文件之间创建同名文件的风险。
Perhaps use
Path.GetTempFileName
instead?That method may throw
IOException
so you should probably catch that at some point. Exactly where depends more on the context in which this code exists.Note that this method also creates the file on disk, so there is no risk that some other process creates an identically named file between this call and the time when the file is written to by your code.
有什么问题:
来自 MSDN Path.GetTempFileName()< /a>:
它确实确保您不会获得已经存在的文件,并且关于您有关故障场景的问题,如果它无法创建这样的文件:
What's wrong with:
From MSDN on Path.GetTempFileName():
It does ensure that you don't get a file that already exists and with regard to your question about failure scenarios, if it cannot create such a file: