Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot delete temporary file after File.Copy in C#

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);
        }
    }
}
like image 512
jveazey Avatar asked May 06 '13 08:05

jveazey


Video Answer


1 Answers

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);
like image 70
Damith Avatar answered Oct 30 '22 01:10

Damith