简体   繁体   中英

The process cannot access the file because it is being used by another process

My app uses File.OpenRead to read a csv file.

This works fine except when the csv file is also open in Excel in which case I get an error

The process cannot access the file 'C:\\test.csv' because it is being used by another process.

What's going on? It makes sense for Excel to block other apps from writing to the file (to prevent conflicts), but why does it stop other apps reading it? Is there any way I can get round it?

Well, this doesnt answer why? , but solves the problem of how . There is another way of reading locked files, like this (the key thing is FileShare.ReadWrite ):

http://coding.infoconex.com/post/2009/04/21/How-do-I-open-a-file-that-is-in-use-in-C

 using(FileStream fileStream = new FileStream(
        "logs/myapp.log",
        FileMode.Open,
        FileAccess.Read,
        FileShare.ReadWrite))
    {
        using(StreamReader streamReader = new StreamReader(fileStream))
        {
            this.textBoxLogs.Text = streamReader.ReadToEnd();
        }
    }

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