.NET e file bloccate... (Italiano (Italian))

.NET e file bloccate...

Friday, 20 February 2004

//

1 minute read

OK, qualcuno può spiegare perché non posso'controllare esplicitamente se posso bloccare un file prima di leggerlo M SK2i .eMSC4 controllare che nessunoMNK5alcun altro stia bloccando il file prima che cerco di leggerlaMRK6 ioMMK7 sto usando la meravigliosa FileSystemWatcher aspettare che i file vengano creati in un directorio prima di spostare un lavoro - bene ma non c'è ' sembra non essere un modo semplice per verificare se il file è 'readable' prima di cominciare a leggereM SK4 Proprio ora il mio modo di fare questa impresa è provare a leggere M- e mettere un blocco di lettura m- sul file usando FileStream e catturare l'errore che lancia quando il file è bloccato da un altro processo...come così...ma questo davvero non mi sembra beneM SK2non mi sento bene . Mi dispiace l'idea di usare eccezioni MSC4che sono anche REALmente lentiMNK5per questo tipo di compitoMEK6perché non lo faMK7t FileStreamMMK8Posso leggere la lista dei blocchi prima di aprire il fileMRK9

        private static int m_ReadAttempts = 0;
        private string  ReadFileFromDisk(string filePath)
        {
            try
            {
                if(!File.Exists(filePath))
                {
                    MessageBox.Show("Sorry, but the file specified " + Environment.NewLine + filePath + Environment.NewLine + "Cannot be found");
                    return string.Empty;
                }
            using(FileStream fs = new FileStream(filePath,FileMode.Open,FileAccess.Read,FileShare.Read))
                {
                        using(StreamReader sr = new StreamReader(fs)) 
                        {
                            string tmpStr = sr.ReadToEnd();
                            sr.Close();
                            m_ReadAttempts =0;
                            return tmpStr;
                        }
                
                }        
            }
            catch(IOException ex)
            {
                    if(m_ReadAttempts < 10)
                {
                    Thread.Sleep(500);
                    m_ReadAttempts++;
                    return ReadFileFromDisk(filePath);
                }
                else
                {
                    throw ex;
                }
            }
        }
Finding related posts...
logo

© 2026 Scott Galloway — Unlicense — All content and source code on this site is free to use, copy, modify, and sell.