c# - 无法在 C# 中的 File.Copy 后删除临时文件

标签 c# .net file-access

将文件复制到临时目录后,我无法删除副本,因为 UnauthorizedAccessException异常(exception)。这里的想法是获取文件的副本,将其压缩然后删除副本,但是在删除 File.Copy 之间的所有代码之后和 File.Delete我仍然得到异常(exception)。退出程序会释放锁并允许我毫无问题地删除副本。

有没有一种方法可以在不导致这种持久锁定的情况下进行复制(并像 LastModified 一样保留文件元数据)?或者释放锁的方法? File.Copy 完成后是否应该锁定复制的文件?

我正在使用面向 .NET Framework 4.0 的 Visual C# 2010 SP1。

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);
        }
    }
}

最佳答案

检查您的 "C:\\test.txt" 文件是否只读。

根据您的评论,这可能是您可以复制但无法删除的原因

试试下面的

File.SetAttributes(tempfile, FileAttributes.Normal);
File.Delete(tempfile);

关于c# - 无法在 C# 中的 File.Copy 后删除临时文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16394880/

相关文章:

Java 相当于 .Net 的 WebClient

windows - 检查目录的正确方法可用于写入

c# - .net c# postback 覆盖绑定(bind)的文本框

javascript - 正则表达式 ['!@#$%*\]\[()-=_+{}:\";?,.\/A-Za-z0-9\s] 允许 < 字符

C# lambda IN 子句错误

c# - 我有一个 Google 服务帐户,如何在服务器端使用 C# 发送电子邮件?

c# - 为什么指定生命周期管理器时类型会注册两次?

excel - 如何使用密码保护将文件 (Excel) 在线 (Apache 服务器) 但用户可以更改文件并保存更改?

c# - 如何拦截对 .NET 程序中文件的访问

c# - RichTextBox 不显示我的所有文本。