.net - Cannot delete temporary file after File.Copy in C# -


after copying file temporary directory, unable delete copy because of unauthorizedaccessexception exception. idea here copy of file, zip , delete copy, after removing code between file.copy , file.delete still getting exception. exiting program frees lock , allows me delete copy without issue.

is there way copy without causing persistent lock (and preserve file metadata lastmodified)? or way release lock? should there lock on copied file after file.copy finishes?

i using visual c# 2010 sp1 targeting .net framework 4.0.

using system; using system.collections.generic; using system.linq; using system.text; using system.net; using system.io; using system.xml;  namespace test {     class program     {         static void main(string[] args)         {             string filename = "c:\\test.txt";             // generate temporary directory name             string directory = path.combine(path.gettemppath(), path.getrandomfilename());             // temporary file path             string tempfile = path.combine(directory, path.getfilename(filename));             // create directory in file system             directory.createdirectory(directory);             // copy input file temporary directory             file.copy(filename, tempfile);             // delete file in temporary directory             file.delete(tempfile);         }     } } 

check "c:\\test.txt" file read or not.

based on comments may reason can copy can't delete

try below

file.setattributes(tempfile, fileattributes.normal); file.delete(tempfile); 

Comments