Я написал программу, которая копирует файлы. Иногда при попытке копирования файла генерируется исключение - «Доступ к пути ... запрещен». (Возможно, потому что другая программа использует этот файл).Доступ к пути отрицается - C#
Примечание: Я запустить программу в качестве администратора
НО!, когда я копирую тот же файл вручную, он работает!
Почему? Что не так с программой?
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);
}
}
}
Возможно, вам следует показать код, если вы действительно хотите, чтобы кто-то что-то сказал об этом, иначе подождите, если кто-то с кристаллическим шаром сможет посмотреть на ваш экран. – Steve