Cannot delete temporary file after File.Copy in C #

After copying the file to a temporary directory, I cannot delete the copy due to a UnauthorizedAccessException . The idea here is to get a copy of the file, zip it, and then delete the copy, but after deleting all the code between File.Copy and File.Delete I still get the exception. Exiting the program releases the lock and allows me to delete the copy without any problems.

Is there a way to copy without this persistent lock (and save file metadata like LastModified)? Or a way to free the castle? Should there be a lock on the copied file after the completion of File.Copy ?

I am using Visual C # 2010 SP1 for the .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 to the temporary directory File.Copy(FileName, tempfile); // Delete file in temporary directory File.Delete(tempfile); } } } 
+4
source share
2 answers

Check the file "C:\\test.txt" read-only or not.

based on your comments, this may be the reason you can copy, but you cannot delete

try below

 File.SetAttributes(tempfile, FileAttributes.Normal); File.Delete(tempfile); 
+5
source

I see that you have already found the answer, but I will add this for reference anyway; A possible alternative approach for you might be to create a copy in the memory stream instead of copying the file to your hard drive.

Using the DotNetZip library , you can do something like this:

 using (var ms = new MemoryStream()) { using (var zip = new ZipFile()) { zip.AddEntry(fileName, data); zip.Save(ms); } } 
0
source

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


All Articles