【问题标题】:C#: Check if a file is not locked and writableC#:检查文件是否未锁定和可写
【发布时间】:2010-11-13 15:25:01
【问题描述】:

我想在开始替换文件之前检查文件列表是否正在使用或不可写。 当然,我知道文件检查和文件复制的时间有可能一个或多个文件将被其他人锁定,但我处理这些异常。我想在文件复制之前运行这个测试,因为完整的文件列表比操作中间的文件替换失败更有可能成功。

你们有没有一个正确方向的例子或提示

【问题讨论】:

标签: c# .net file


【解决方案1】:

无法保证您获得的列表在任何时候都会在下一秒保持不变,因为当您回到他们身边时其他人可能会控制文件。

我看到了一种方法 - 通过获取相应的 FileStream 对象来“锁定”要替换的文件。这样,您可以确保通过打开所有“可用”文件来锁定它们,然后您可以按照您想要的方式替换它们。

public void TestGivenFiles(List<string> listFiles)
{
  List<FileStream> replaceAbleFileStreams = GetFileStreams(listFiles);


    Console.WriteLine("files Received = " + replaceAbleFileStreams.Count);
    foreach (FileStream fileStream in replaceAbleFileStreams)
    {
        // Replace the files the way you want to.
        fileStream.Close();
    }
}

public List<FileStream> GetFileStreams(List<string> listFilesToReplace)
{
    List<FileStream> replaceableFiles = new List<FileStream>();
    foreach (string sFileLocation in listFilesToReplace)
    {
        FileAttributes fileAttributes = File.GetAttributes(sFileLocation);
        if ((fileAttributes & FileAttributes.ReadOnly) != FileAttributes.ReadOnly)
        { // Make sure that the file is NOT read-only
            try
            {
                FileStream currentWriteableFile = File.OpenWrite(sFileLocation);
                replaceableFiles.Add(currentWriteableFile);
            }
            catch 
            {
                Console.WriteLine("Could not get Stream for '" + sFileLocation+ "'. Possibly in use");
            }
        }
    }
    return replaceableFiles;
}

也就是说,您最好尝试将它们一一替换,而忽略那些您不能替换的。

【讨论】:

    【解决方案2】:

    您必须打开每个文件进行写入才能对此进行测试。

    【讨论】:

      【解决方案3】:
      【解决方案4】:

      读一个字节,写同一个字节?

      【讨论】:

        猜你喜欢
        • 2017-03-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-28
        相关资源
        最近更新 更多