5

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);
        }
    }
}
jveazey
  • 5,398
  • 1
  • 29
  • 44

2 Answers2

8

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);
Damith
  • 62,401
  • 13
  • 102
  • 153
  • How come that " Exiting from the program frees the lock and allows me to delete the copy without issue." ? – VdesmedT May 06 '13 at 11:51
0

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

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

using (var ms = new MemoryStream())
{
    using (var zip = new ZipFile())
    {
        zip.AddEntry(fileName, data);
        zip.Save(ms);
    }
}
Kjartan
  • 18,591
  • 15
  • 71
  • 96