从C: oot目录开始迭代文件系统
本文关键字:开始 迭代 文件系统 oot | 更新日期: 2023-09-27 18:22:06
我即将完成这个项目,但我有一个问题无法解决。例如,如果我运行我的程序并在"我的文档"中开始迭代。一切都很完美。该程序进行迭代,将结果写入csv文件,就像告诉它一样。然而,如果我在C:''开始迭代(你会看到下面我写的是为了"捕获"未授权访问异常),我编码的消息会弹出,告诉我我没有访问任何目录的权限,它甚至没有创建csv文件。这是我的代码,任何帮助都会很棒。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace FileIterator
{
class Iterator
{
public class MyItem
{
public static string it { get; set; }
}
public class Record
{
public long fileSize { get; set; }
public string fileName { get; set; }
}
static List<Record> fileList = new List<Record>();
static string longest = " ";
static string shortest = " ";
public static void Iterate(string dir_tree)
{
Stack<string> dirs = new Stack<string>(20);
if (!Directory.Exists(dir_tree))
{
MessageBox.Show("The directory you selected does not exist.", "Directory Selection Error",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
dirs.Push(dir_tree);
while (dirs.Count > 0)
{
string currentDir = dirs.Pop();
string[] subDirs;
try
{
subDirs = Directory.GetDirectories(currentDir);
}
catch (UnauthorizedAccessException)
{
MessageBox.Show("You do not have permission to access this folder " + currentDir, "Directory Permission Error",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
continue;
}
catch (DirectoryNotFoundException)
{
MessageBox.Show("The current directory does not exist", "Directory Not Found",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
continue;
}
string[] files = null;
try
{
files = System.IO.Directory.GetFiles(currentDir);
}
catch (UnauthorizedAccessException)
{
MessageBox.Show("You do not have permission to access this folder " + currentDir, "Directory Permission Error",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
continue;
}
catch (DirectoryNotFoundException)
{
MessageBox.Show("The current directory does not exist", "Directory Not Found",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
continue;
}
foreach (string file in files)
{
try
{
FileInfo fi = new FileInfo(file);
fileList.Add( new Record {
fileName = fi.Name,
fileSize = fi.Length
});
}
catch (FileNotFoundException)
{
MessageBox.Show("The current file does not exist" + file, "File Not Found",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
continue;
}
}
foreach (string str in subDirs)
dirs.Push(str);
}
using (var writer = new StreamWriter(@"C:'files.csv"))
{
writer.WriteLine("Name,Size"); // Header
var query = fileList.OrderBy(r => r.fileName);
foreach (Record record in query)
{
writer.WriteLine("'"{0}'",{1}", record.fileName, record.fileSize);
}
}
}
}
}
如果您在Windows 7或Vista上运行此应用程序,如果不出现提示您使用管理员权限运行应用程序的消息,您将无法获得写入许多目录的权限。
若要查看这是否是您遇到的问题,请以管理员身份启动Visual Studio(右键单击"开始"菜单中的VS并选择"以管理员身份运行")。然后,通过Visual Studio打开你的项目并运行它。如果它运行并创建你的CSV文件,那么问题出在你没有提升的权限。如果错误消息仍然出现,那么您就知道这是其他情况。
(不过,我建议不要测试"C:''中的所有内容"——在程序文件中创建一个目录,并将其用作测试此问题的沙箱)。