Safe stream update of file

前端 未结 8 1383
别那么骄傲
别那么骄傲 2020-11-30 14:37

We perform updates of large text files by writing new records to a temp file, then replacing the old file with the temp file. A heavily abbreviated version:

         


        
8条回答
  •  佛祖请我去吃肉
    2020-11-30 15:25

    This code snippet shows a technique for getting exclusive access to a file (read in this case):

    // Try to open a file exclusively
    FileInfo fi = new FileInfo(fullFilePath);
    
    int attempts = maxAttempts;
    do
    {
        try
        {
            // Try to open for reading with exclusive access...
            fs = fi.Open(FileMode.Open, FileAccess.Read, FileShare.None);
        }
        // Ignore any errors... 
        catch { }
    
        if (fs != null)
        {
            break;
        }
        else
        {
            Thread.Sleep(100);
        }
    }
    while (--attempts > 0);
    
    // Did we manage to open file exclusively?
    if (fs != null)
    {
        // use open file....
    
    }
    

提交回复
热议问题