简体   繁体   中英

File.Open throws IOException, but file is never open/shown

I am doing a simple test in code, as follows:

try
{
    File.Open(path);
}
catch (Exception ex)
{
    MessageBox.Show(ex.ToString());
}

path is a string declared above. This routine is called when a button is pressed, and the first time it is called, it "works normally" (in quote, because although it doesn't throw an exception, the file is never open/shown). The second time it is pressed, the following exception is thrown:

System.IO.IOException: The process cannot access the file because it is being used by another process.

However, the file is actually never open. I monitor it with Task Manager, and no instance of the file is ever exhibited.

I tried using using (File.Open(path)) {} , but to no success.

Can anybody help me? It seems like a basic mistake I'm doing, but I can't find it.

UPDATE

Lasse Vågsæther Karlsen provided the correct answer, pointing out that my mistake was actually about the concept, not the code. Thanks!

I think you've misunderstood what File.Open does.

This method will open the file for reading by your program . In other words, that method will return a Stream object which you can use to read from and write to that file.

At the end of that operation, you have to close it, which is what using would do for you.

However, I'm guessing that this is not what you want to do. You keep mentioning that the file does not open, and that you're using the Task Manager to look for the file, not seeing it.

You want Process.Start instead. You're trying to open either another executable, such as notepad.exe , or you're trying to open a document, like readme.txt , that's why you're not using the result of calling that method, and why you're using the Task Manager to look for it.

So, assuming you still want to catch exceptions, this is what you should do:

try
{
    Process.Start(path);
}
catch (Exception ex)
{
    MessageBox.Show(ex.ToString());
}

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