我编写了一个复制文件的程序。有时,在尝试复制文件时会引发异常 - “访问路径...被拒绝”。 (可能是因为另一个程序使用此文件)。
注意:我以管理员身份运行该程序
但是!当我手动复制同一文件时,它可以工作!
为什么?程序出了什么问题?try
{
CopyClass.Copy(m_FilesSources[i].Path, m_FilesDestinations[i], true, m_FilesSources[i].Postfix);
}
catch (Exception ex)
{
isAccessDenied = true;
tbLog.Text += " - " + ex.Message + "\n";
}
class CopyClass
{
public static bool Copy(string sourceDirPath, string destDirPath, bool copySubDirs, string postfix)
{
if (postfix == null)
{
FileCopy(sourceDirPath, destDirPath, copySubDirs);
return true;
}
DirectoryCopy(sourceDirPath, destDirPath, copySubDirs, postfix);
return true;
}
public static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs, string postfix)
{
// Get the subdirectories for the specified directory.
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories();
// If the destination directory doesn't exist, create it.
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
// Get the files in the directory and copy them to the new location.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = System.IO.Path.Combine(destDirName, file.Name);
if (postfix == ".")
{
file.CopyTo(temppath, copySubDirs);
}
else if (file.Name.EndsWith(postfix))
{
file.CopyTo(temppath, copySubDirs);
}
}
// If copying subdirectories, copy them and their contents to new location.
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
string tempPath = System.IO.Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, tempPath, copySubDirs, postfix);
}
}
}
public static void FileCopy(string sourceFileName, string destDirName, bool overwrite)
{
string destFileName = destDirName + sourceFileName.Substring(sourceFileName.LastIndexOf('\\') + 1);
// If the destination directory doesn't exist, create it.
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
System.IO.File.Copy(sourceFileName, destFileName, overwrite);
}
}
}
最佳答案
问题是我尝试覆盖的文件是只读的。为了解决这个问题,我手动将目标文件的属性更改为正常(不是只读):
if (File.Exists(destFileName))
{
File.SetAttributes(destFileName, FileAttributes.Normal); // Makes every read-only file into a RW file (in order to prevent "access denied" error)
}
希望这对您有所帮助。
关于c#-4.0 - 访问路径被拒绝 - C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26828634/