简体   繁体   中英

C# Creating and opening file in isolation throws IOException

I made this small program that demonstrates my problem. It creates the file, and then tries to open it at the same address. An IOException Sharing violation on path is thrown when it tries to open the file. Why does this happen? I can see that the file is being created.

using System;
using System.IO;

namespace FileTestProject
{
class MainClass
{
    private static string address = "/Users/jamessullivan/Desktop/testFile.dat";

    public static void Main ()
    {
        File.Create(address);
        FileStream file = File.Open(address, FileMode.Open);
    }
}
}

You can see problem looking into documentation.

Although your example is meaningless, here is an explanation of problem.

Create.File(string) returns FileStream which holds unmanaged resource called file handle so you can't create another FileStream which which should hold the same handle.

Thous, you should free up the resource after reusing it.

This is a simple consept:

using(File.Create(address))
{}

using(FileStream file = File.Open(address, FileMode.Open)
{
}

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