文件只读时进行拷贝报错,解决方法如下:
设置文件属性为正常 然后在进行拷贝
/// <summary>
/// 拷贝文件夹
/// </summary>
/// <param name="sourceDirectory"></param>
/// <param name="targetDirectory"></param>
public static bool DirectoryCopy(string sourceDirectory, string targetDirectory)
{
if (!Directory.Exists(sourceDirectory))
{
return false;
}
if (!Directory.Exists(targetDirectory))
{
Directory.CreateDirectory(targetDirectory);
}
DirectoryInfo sourceInfo = new DirectoryInfo(sourceDirectory);
//拷贝源路径下的文件
FileInfo[] fileInfo = sourceInfo.GetFiles();
foreach (FileInfo fiTemp in fileInfo)
{
string sSrcFilePath = String.Format("{0}\\{1}", sourceDirectory, fiTemp.Name);
string sTarFilePath = String.Format("{0}\\{1}", targetDirectory, fiTemp.Name);
//去除文件的只读属性
//System.IO.File.SetAttributes(sSrcFilePath, System.IO.FileAttributes.Normal);
FileAttributes attributes = File.GetAttributes(sSrcFilePath);
attributes = attributes & ~FileAttributes.ReadOnly;
File.SetAttributes(sSrcFilePath, attributes);</span>
File.Copy(sSrcFilePath, sTarFilePath, true);
}
//拷贝源路径下的文件夹
DirectoryInfo[] diInfo = sourceInfo.GetDirectories();
foreach (DirectoryInfo diTemp in diInfo)
{
string sourcePath = diTemp.FullName;
string targetPath = diTemp.FullName.Replace(sourceDirectory, targetDirectory);
Directory.CreateDirectory(targetPath);
DirectoryCopy(sourcePath, targetPath);
}
return true;
}
参考链接:
https://msdn.microsoft.com/en-us/library/system.io.file.setattributes%28v=vs.110%29.aspx