仅当文件不存在时才创建
我只想创建一个尚不存在的文件。
像这样的代码:
if (!File.Exists(fileName))
{
fileStream fs = File.Create(fileName);
}
将其打开以应对竞争条件,以防文件将在“if”到“create”之间创建。
我怎样才能避免它?
编辑:
此处不能使用锁,因为它是不同的进程(同一应用程序的多个实例)。
I want to create a file ONLY if it doesn't already exists.
A code like:
if (!File.Exists(fileName))
{
fileStream fs = File.Create(fileName);
}
Leave it open for a race-condition in case the file will be created between the "if" to the "create".
How can I avoid it?
EDIT:
locks can't be used here because it's a different processes (multiple instances of the same application).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您还可以使用
但是,您应该研究线程锁定,就好像多个线程尝试访问该文件一样,您可能会遇到异常。
You can also use
However, you should look into thread locking as if more than one thread tries to access the file you'll probably get an exception.
Kristian Fenn 的答案几乎就是我所需要的,只是文件模式不同。这就是我一直在寻找的:
Kristian Fenn answer was almost what I needed, just with a different FileMode. This is what I was looking for:
这难道不是更好的解决方案吗?另请注意
using(var stream...)
使用它来关闭流以避免 IO 异常。Is this not a better solution. Also notice the
using(var stream...)
Use it to close the stream to avoid IO Exceptions.如果创建文件的争用尝试位于同一进程中,您可以在代码周围使用
lock
语句来防止争用。如果没有,调用 File.Create 时偶尔可能会出现异常。只需适当处理该异常即可。即使您在文件确实存在时处理异常,也可能建议在创建之前检查文件是否存在,因为抛出异常的成本相对较高。仅当竞争条件的概率较低时才建议这样做。
If the contending attempts to create the file are in the same process, you can use a
lock
statement around your code to prevent contention.If not, you may occasionally get an exception when you call File.Create. Just appropriately handle that exception. Checking whether the file exists before creating is probably advisable even if you are handling an exception when the file does exist because a thrown exception is relatively expensive. It would not be advisable only if the probability of the race condition is low.
首先,您使用 Lock 或 Monitor.Enter 或 TryEnter API 来锁定该部分代码。
其次,您可以将 FileStream API 与 FileMode.OpenOrCreate API 结合使用。如果文件存在,则仅使用它,否则仅创建它。
First you Lock or Monitor.Enter or TryEnter APIs to lock the portion of the code.
Second you can use FileStream API with FileMode.OpenOrCreate API. If the file exists, it just uses it or else it just creates it.