简体   繁体   English

C#打开文件异常

[英]C# open file exception

i have a C# form having troubles with file operations. 我有一个C#表单,文件操作有麻烦。

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. 当文件已经存在时,程序运行正常;当文件不存在时,程序进入catch异常。

Is ReadAllTest() not supposed to check wether file exists or not ? ReadAllTest()是否不应该检查文件是否存在? Should i add a special Exception catch "filenotfound", and create it ? 我应该添加一个特殊的异常捕获“ filenotfound”并创建它吗?

The MSDN docs for File.ReadAllText state explicitly that it will throw a FileNotFoundException if the file doesn't exist. 用于File.ReadAllTextMSDN文档明确声明,如果文件不存在,它将抛出FileNotFoundException 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. 最好不要依赖Exception来进行易于检查的事情。 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. 一方面是因为潜在的性能问题(捕获异常是不是一个简单的测试,如果慢了许多 ),都对代码的清晰性和可读性-一个的if / else分支通常比一个try / catch块更容易理解和结构。 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 ;    
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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