After copying a file to a temporary directory, I am unable to delete the copy because of an UnauthorizedAccessException exception. The idea here is to get a copy of the file, zip it and then delete the copy, but after removing all the code between File.Copy
and File.Delete
I am still getting the exception. Exiting from the program frees the lock and allows me to delete the copy without issue.
Is there a way to copy without causing this persistent lock (and preserve file metadata like LastModified)? Or a way to release the lock? Should there even be a lock on the copied file after File.Copy
finishes?
I am 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 to the temporary directory
File.Copy(FileName, tempfile);
// Delete file in temporary directory
File.Delete(tempfile);
}
}
}
Check your "C:\\test.txt"
file for read only or not.
based on your comments this may be the reason you can copy but you can't delete
try with below
File.SetAttributes(tempfile, FileAttributes.Normal);
File.Delete(tempfile);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With