我写了一个复制文件的程序。有时,在尝试复制文件时会抛出异常 - “拒绝访问路径...”。 (可能是因为另一个程序使用此文件)。
注意:我以管理员身份运行程序
但是!当我手动复制同一个文件时,它可以正常工作!
为什么呢?该计划有什么问题?
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);
}
}
}
答案 0 :(得分:3)
问题是我试图覆盖的文件是只读的。为了解决这个问题,我手动将目标文件的属性更改为正常(不是只读):
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)
}
希望这有用。
答案 1 :(得分:0)
您很可能正在尝试修改/写入/读取应用程序无法访问的文件,因为该应用程序是在受限用户下运行的。
尝试以管理员身份运行该程序。 (右键单击 - >以管理员身份运行。)
您还可以以管理员身份运行VS,这将强制应用程序也以管理员身份运行。