c# - File Still Locked Despite putting StreamReader in Using -


my program goes through files in folder, reads them, , without altering information moves them location under different name. cannot use file.move method because following ioexception:

the process cannot access file because being used process.

this how reading file , adding lines list<string>:

list<string> lines = null; using (var fs = new filestream(filepath, filemode.open, fileaccess.read, fileshare.readwrite))     using (var sr = new streamreader(fs, encoding.default))     {         lines = new list<string>();         while (!sr.endofstream)             lines.add(sr.readline());     } 

and function move file:

public static bool archivefile(string filepath, string archivefolderlocation) {     if (!directory.exists(archivefolderlocation))         directory.createdirectory(archivefolderlocation);     try     {         string timestamp = string.format("{0:yyyy-mm-dd hhmmss}", datetime.now);         string newfilename = path.getfilenamewithoutextension(filepath) + " " + timestamp;         string destination = string.format("{0}\\{1}{2}", archivefolderlocation, newfilename, path.getextension(filepath));         file.move(filepath, destination);         return true;     }     catch (exception ex)     {         return false;     } } 

i thought using using statement supposed garbage-collect , release file after being used. how can release file can move , why file stays locked?

solved:

got it. somewhere between these 2 calls opening textreaderobject without disposing it.

i thought using using statement supposed garbage-collect , release file after being used. how can release file can move , why file stays locked?

not really. using statement nothing :

try { var resource = new someresource(); }   { resource.dispose(); // not gc.collect(); } 

it works fine looks file opened other place in code...

p.s. way can do:

list<string> lines = file.readalllines().tolist();


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -