我使用以下代码访问4个文件夹。但是,有1个私人文件夹,只有老年人可以访问它。如何避免该文件夹并仍可访问其他4个文件夹?
class Program
{
const string FILENAME = @"H:\Personal\text.xml";
const string FOLDER = @"F:\Apps";
static XmlWriter writer = null;
static void Main(string[] args)
{
XmlWriterSettings settings = new XmlWriterSettings
{
Indent = true
};
writer = XmlWriter.Create(FILENAME, settings);
writer.WriteStartDocument(true);
DirectoryInfo info = new DirectoryInfo(FOLDER);
WriteTree(info);
writer.WriteEndDocument();
writer.Flush();
writer.Close();
Console.WriteLine("Enter Return");
Console.ReadLine();
}
编辑:(WriteTree代码) 我添加了其余代码,其中还包含WriteTree代码。 我无权访问管理文件夹。
static long WriteTree(DirectoryInfo info)
{
long size = 0;
writer.WriteStartElement("Folder");
try
{
writer.WriteAttributeString("name", info.Name);
writer.WriteAttributeString("numberSubFolders", info.GetDirectories().Count().ToString());
writer.WriteAttributeString("numberFiles", info.GetFiles().Count().ToString());
writer.WriteAttributeString("date", info.LastWriteTime.ToString());
foreach (DirectoryInfo childInfo in info.GetDirectories())
{
size += WriteTree(childInfo);
}
}
catch (Exception ex)
{
string errorMsg = string.Format("Exception Folder : {0}, Error : {1}", info.FullName, ex.Message);
Console.WriteLine(errorMsg);
writer.WriteElementString("Error", errorMsg);
}
FileInfo[] fileInfo = null;
try
{
fileInfo = info.GetFiles();
}
catch (Exception ex)
{
string errorMsg = string.Format("Exception FileInfo : {0}, Error : {1}", info.FullName, ex.Message);
Console.WriteLine(errorMsg);
writer.WriteElementString("Error", errorMsg);
}
if (fileInfo != null)
{
foreach (FileInfo finfo in fileInfo)
{
try
{
writer.WriteStartElement("File");
writer.WriteAttributeString("name", finfo.Name);
writer.WriteAttributeString("size", finfo.Length.ToString());
writer.WriteAttributeString("date", info.LastWriteTime.ToString());
writer.WriteEndElement();
size += finfo.Length;
}
catch (Exception ex)
{
string errorMsg = string.Format("Exception File : {0}, Error : {1}", finfo.FullName, ex.Message);
Console.WriteLine(errorMsg);
writer.WriteElementString("Error", errorMsg);
}
}
}
writer.WriteElementString("size", size.ToString());
writer.WriteEndElement();
return size;
}
}
}
错误: 异常文件夹:错误:拒绝访问该路径。
答案 0 :(得分:2)
您可以在使用richardwiden的答案写入文件之前检查权限:Checking for directory and file write permissions in .NET
或者您可以在try catch
函数中使用WriteTree()
忽略UnauthorizedAccessException
例外,例如:
try {
writer.WriteAttributeString("name", info.Name);
[...]
} catch (Exception ex) {
// If is a permission error, ignore exception
if (ex is UnauthorizedAccessException)
return size;
// custom error log
string errorMsg = string.Format("Exception Folder : {0}, Error : {1}", info.FullName, ex.Message);
Console.WriteLine(errorMsg);
writer.WriteElementString("Error", errorMsg);
}