简体   繁体   中英

C# open file exception

i have a C# form having troubles with file operations.

Here's how it works :

When the user click on the "start" button, the program begins. It opens the file (if exists?), check the header of this file and modify a boolean if this header exists.

Then, it opens the file again, to put a header (if non exists) and other infos, or just infos (if header exists)

Here's the code :

public bool enteteExiste = false;

private void start_Click(object sender, EventArgs e)
{
    try
    {
       verifieEntete();
       //INSERTION DE L'ENTETE DU FICHIER CSV
       writeToCsv = new StreamWriter(boxFilePath.Text + "\\" + filename, true);
       canAcces = true;
    }
    catch (Exception)
    {
       MessageBox.Show("Droits d'accès au dossier insuffisant OU fichier déjà ouvert" + Environment.NewLine + "Assurez vous d'avoir fermé le fichier et de disposer des droits requis" + Environment.NewLine + "Arrêt de la procédure");
    }
}

public void verifieEntete()
{
    string absolutFilePath = boxFilePath.Text + '\\' + filename;
    String[] fileContent = File.ReadAllText(absolutFilePath).Split(',');
    for (int i = 0; i < fileContent.Length; i++)
        if (fileContent[i].Contains("MAC;SERIAL;IP;MODELE;MODULE-EXT"))
            enteteExiste = true ;    
}

When file already exists, program runs perfectly, When file does not exists, program goes into catch Exception.

Is ReadAllTest() not supposed to check wether file exists or not ? Should i add a special Exception catch "filenotfound", and create it ?

The MSDN docs for File.ReadAllText state explicitly that it will throw a FileNotFoundException if the file doesn't exist. So yes, you have to explicitly check for its existence.

It's best not to rely on Exceptions for something that can easily be checked beforehand. Both because of potential performance issues (catching an exception is a lot slower than a simple if test), and both for code clarity and readability - an if/else branching is usually easier to understand and structure than a try/catch block. This way you can handle the error before it happens, and fix it (like, say, creating the file if necessary)

public void verifieEntete()
{
    string absolutFilePath = boxFilePath.Text + '\\' + filename;
    if (!File.Exists(absolutFilePath) // <--- ADD EXPLICIT CHECK
    {
         // Create the file here. 
    }

    // Now we know the file is *sure* to exist, because we handled it 
    // explicitly.
    String[] fileContent = File.ReadAllText(absolutFilePath).Split(',');
    for (int i = 0; i < fileContent.Length; i++)
        if (fileContent[i].Contains("MAC;SERIAL;IP;MODELE;MODULE-EXT"))
            enteteExiste = true ;    
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM