How to check if a file is used in C #?

How to check if the excel file I'm working on (manipulating its data, deleting it or overwriting it) is being used by another program? And how to let him go from the same?

Please use C #, please.

+4
source share
1 answer

Trying to open flags for writing. If this fails, the file is "taken" by some other process.

FileStream fileStream = null; try { fileStream = new FileStream(@"c:\file.txt", FileMode.Open, FileAccess.Write); } catch (UnauthorizedAccessException e) { // The access requested is not permitted by the operating system // for the specified path, such as when access is Write or ReadWrite // and the file or directory is set for read-only access. } finally { if (fileStream != null) fileStream.Close (); } 

PS Just found a very similar question, basically the same answer:

C #: Is there a way to check if a file is being used?

+4
source

Source: https://habr.com/ru/post/1302462/


All Articles