簡體   English   中英

重命名文件和文件共享(文件流)

[英]Renaming files and filesharing (filestream)

我正在使用文件流來訪問文件(創建md5 ComputeHash)。 如果我在此期間嘗試重命名文件(由於正在訪問文件而失敗)。 到目前為止,一切都很好,但是當我在關閉原始文件流后嘗試重新打開文件時,我得到了在另一個進程中打開文件的信息。

碼:

using (Stream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) {
    MD5 md5 = MD5.Create();
    byte[] mymd5computed = md5.ComputeHash(fileStream);
    ......
}
Thread.Sleep(50);

Thread a = new Thread (()=>{(FileStream sourceStream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)){....} });

就像我說的,如果在計算MD5的過程中嘗試重命名文件,我會得到該文件仍處於鎖定狀態的信息。

關閉流時,有時不會立即釋放對文件的鎖定,因此可以使用一些其他解決方案,直到再次訪問該文件。 其中之一在此處進行了說明: http : //www.codeproject.com/Tips/164428/C-FileStream-Lock-How-to-wait-for-a-file-to-get-re

概括:

public static void Lock(string path, Action<FileStream> action) {
    var autoResetEvent = new AutoResetEvent(false);

    while(true)
    {
        try
        {
            using (var file = File.Open(path,
                                        FileMode.OpenOrCreate,
                                        FileAccess.ReadWrite,
                                        FileShare.Write))
            {
                action(file);
                break;
            }
        }
        catch (IOException)
        {
            var fileSystemWatcher =
                new FileSystemWatcher(Path.GetDirectoryName(path))
                        {
                            EnableRaisingEvents = true
                        };

            fileSystemWatcher.Changed +=
                (o, e) =>
                    {
                        if(Path.GetFullPath(e.FullPath) == Path.GetFullPath(path))
                        {
                            autoResetEvent.Set();
                        }
                    };

            autoResetEvent.WaitOne();
        }
    } 
}

樣品使用:

Lock(@"c:\file",
        (f) =>
            {
                try
                {
                    f.Write(buf, 0, buf.Length);
                }
                catch(IOException ioe)
                {
// handle IOException
                }
            });

希望能幫助到你! :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM