# .NET e file bloccate...

<datetime class="hidden">2004-02-20T00:00</datetime>

<!-- category -- mostlylucidcouk, Imported, .NET, C# -->
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](http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemiofilesystemwatcherclasstopic.asp) 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](http://msdn.microsoft.com/library/en-us/cpref/html/frlrfSystemIOFileStreamClassTopic.asp) 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;
                }
            }
        }
```