asp.net - File is being used by another process in c# -


i trying delete file in c#, receiving message file used process. want check if files exists , close it. using following function in order check if file open:

public static bool isfileinuse(string path)     {         if (string.isnullorempty(path))             throw new argumentexception("'path' cannot null or empty.", "path");          try         {             using (var stream = new filestream(path, filemode.open, fileaccess.read)) { }         }         catch (ioexception)         {             return true;         }          return false; } 

and trying when file in use close it:

bool checking = isfileinuse(file ); file.create(file ).close(); if (file.exists(file)) {        file.delete(file ); } 

i got issues in file.create line, receiving message:

file being used process.

edit: trying use lock approach in order delete file. suppose delete file inside lock statement? how can use lock statement?

why suppose reading operation fail if file in use while writing operation not? file.create() fail new filestream() failed before...

see ioexception: process cannot access file 'file path' because being used process.

note check fail if other process didn't open file exclusively (check fileshare enumeration): file may open shared reading, writing , deleting (for example may able read concurrently not writing other process may let delete file...).

to close open file can disruptive other process, may crash, nicely handle problem or...anything else (silently ignore error , produce random output, open file again , on...) possible in c#? yes p/invoke...

1) let's find handle file want unlock. use ntquerysysteminformation() , enumerate handles until find 1 refers file.

2) duplicate handle valid in own process using duplicatehandle().

3) close create handle specifying duplicate_close_source, close both handle , original 1 (of course if process has enough permissions).

4) check if file closed calling ntquerysysteminformation() again, if not may need directly close parent process.


Comments

Popular posts from this blog

Hatching array of circles in AutoCAD using c# -

ios - UITEXTFIELD InputView Uipicker not working in swift -

Python Pig Latin Translator -