c#: System.unauthorizedaccesssexception:访问路径被拒绝.移动或文件删除



我需要创建一个小型控制台应用程序来将文件移动到单独的文件夹中。一切正常,我可以复制文件,直到我尝试文件。移动或文件。删除文件,我捕获systemunauthorizedaccessexception。

  1. 从代码
  2. 更改文件夹权限从。net Core切换到。net Framework
  3. 通过右键单击->Security->Advance手动添加文件夹权限
  4. 试图改变文件夹的只读属性(它总是恢复到只读,我不能解决这个问题)

我不知道我还能尝试什么,也不知道如何解决这个问题。我写的代码在

下面
var pngFiles = Directory.GetFiles(@"C:UsersMSI_PCDesktopTest", "*.png",
SearchOption.AllDirectories);
foreach (var pngFile in pngFiles)
{
Console.WriteLine(pngFile);
var fileName = Path.GetFileName(pngFile);
var newFolder = Path.Combine(@"C:UsersMSI_PCDesktopTest",
Path.GetFileNameWithoutExtension(fileName));
Directory.CreateDirectory(newFolder);
var newFileName = Path.Combine(@"C:UsersMSI_PCDesktopTest",
Path.GetFileNameWithoutExtension(fileName), fileName);
File.Copy(pngFile, newFileName, true); //yes, I can use move and have 1 line of code instead of 2. But I need file to be copied, and this line of code works fine
File.Delete(pngFile); // System.UnauthorizedAccessException. File.Move throws the same exception
}

试试这个代码

private void Copy()
{
var pngFiles = Directory.GetFiles(@"C:UsersAdministratorDesktop", "*.png", SearchOption.AllDirectories);
foreach (var pngFile in pngFiles)
{
Console.WriteLine(pngFile);
var fileName = Path.GetFileName(pngFile);
var newFolder = Path.Combine(@"D:NewPic");
Directory.CreateDirectory(newFolder);
string DestPath = newFolder + "\" + fileName;
byte[] buffer = new byte[2014 * 1024];
using (FileStream source = new FileStream(pngFile, FileMode.Open, FileAccess.Read, FileShare.Delete))
{
using (FileStream dest = new FileStream(DestPath, FileMode.CreateNew, FileAccess.Write, FileShare.Delete))
{
int currentBlockSize = 0;
while ((currentBlockSize = source.Read(buffer, 0, buffer.Length)) > 0)
{
dest.Write(buffer, 0, currentBlockSize);
}
dest.Close();
}
source.Close();
}
File.Delete(pngFile); // System.UnauthorizedAccessException. File.Move throws the same exception
}
}

相关内容

  • 没有找到相关文章