在netshare上创建文件,需要文件存在例外 [英] Create File on netshare, need exception on file exists

查看:61
本文介绍了在netshare上创建文件,需要文件存在例外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码:

I''ve some code:

If(!File.Exists(FILE_ON_NETSHARE))
{
    int val = calc_something();
    try{
        File.WriteAllText(FILE_ON_NETSHARE, "File Created and Calced: " + val);
	created = true;
    }
    cache () {
	// handle
    }
}



首先,它应检查Netshare中是否存在文件.
如果不是,则应计算一个值并将其写入新创建的文件.

但是有时在calc_something()期间,该文件是由另一个进程创建的.
但是w文件已被覆盖,但是我希望有一个异常以另一种方式处理此问题.

但是File.WriteAllText();会毫无例外地覆盖文件.



First it should check if a file Exists on the Netshare.
If not it should calc a value and and write it to the new created file.

But sometimes the file is created by another process, during calc_something().
But thew file is overwritten, but I want an exception to handl this problem in another way.

But File.WriteAllText(); overwrittes the file without exception.

推荐答案

您可以使用File.Exists("filename.ext")检查文件是否存在.

每个人都覆盖一个特定文件的内容不是一个好主意,请尝试使用某种指示符将其附加到文件上,以指示是谁添加了该行等.


You can check if a file exists with File.Exists("filename.ext").

It''s not a good idea for everyone to overwrite the contents of a specific file, try appending to the file with some sort of deliminator indicating who added the line etc.

Edited :
if(File.Exists(NETSHARE)==false)
{
   File.WriteAllText(FILE_ON_NETSHARE, "File Created and Calced: " + val);
   created = true;
}
else
{
   // handle
}


在执行计算时,您似乎需要在共享文件中写入占位符,以便其他进程知道其他人已经声明了该占位符.
的方法
It looks like you need to write a placeholder to the shared file while you''re doing the calculation so that other processes know that someone else has already claimed it. The method of
if (File.Exists(...))
    File.WriteAllText(...)


这是一项非原子操作,因此总会有人在您的检查和写入之间写入文件.我为您提供了两种可能的解决方案:
(a)创建文件时不包含任何内容,而不是仅检查文件是否存在,并使用抛出该文件是否已存在的方法.如果成功,则可以进行计算,然后覆盖使用结果创建的文件.当其他进程在进行计算之前尝试打开/写入文件时,它们会看到文件已存在并退出.
(b)假设该文件不存在,请进行计算,然后以抛出该文件(如果该文件已经存在)的方式写入该文件.

使用选项A进行计算时将有一个空文件,使用选项B则冒着进行计算然后丢弃结果的风险.

这是选项B:


is an non-atomic operation so there will always be the chance someone writes the file between your checking and writing. I see two possible solutions for you:
(a) instead of just checking for file existence, create the file with nothing in it and use a method that throws if the file already exists. If that succeeds then you can do the calculation and then overwrite the file you created with the results. When other processes try to open/write the file before they do the calculation they''ll see the file already exists and exit.
(b) assume the file doesn''t exist, do the calculation and then write the file in a way that throws if it already exists.

With Option A you''ll have an empty file while you''re doing you''re calculation, with Option B you run the risk of doing the calculation and then throwing away the result.

Here''s Option B:

static void Main()
{
    // this example assumes the share specified here exists and we have the ability to write to it
    string path = @"\\" + Environment.MachineName + @"\Share\Test.txt";

    int val = DoSomeCalculation();
    try
    {
        // assume the file doesn't exist, if it does then an exception will be thrown here
        using (FileStream fs = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.ReadWrite))
        {
            using (StreamWriter sw = new StreamWriter(fs))
            {
                sw.Write("File Created and Calced: " + val);
                sw.Close();
            }
            fs.Close();

            Console.WriteLine("File created.");
        }
    }
    catch (IOException)
    {
        // this will be thrown if the file already exists (this includes if another process 
        // using the same code currently has it open). 
        Console.WriteLine("File already exists.");
    }

    Console.WriteLine();
    Console.WriteLine("Press ENTER to continue ...");
    Console.Read();

    return;
}


它演示了如何编写文件以及如何将其抛出(如果已存在);修改此代码以实现选项A留给读者练习.别忘了还要检查其他异常,例如UnauthorizedAccess.


It demonstrates how to write a file and have it throw if it already exists; modifying this to implement Option A is left as an exercise for the reader. Don''t forget to check for other exceptions as well, like UnauthorizedAccess.


这篇关于在netshare上创建文件,需要文件存在例外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆