【发布时间】:2023-03-11 06:43:01
【问题描述】:
我非常接近完成这个项目,但是我有一个我无法解决的问题。 例如,如果我运行我的程序并在我的文档中开始迭代。一切都很完美。程序迭代,将结果写入 csv 文件,就像告诉它一样。但是,如果我在 C:\ 开始迭代(您将在下面看到我写的“捕获” UnauthorizedAccessException),我编写的消息会弹出,告诉我我无权访问任何目录,它甚至不创建 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);
}
}
}
}
}
【问题讨论】:
-
运行应用的用户有什么权限?
-
@Joe 这是一个很好的问题,因为我是 C# 的菜鸟,我不知道。我该如何检查?
-
您是这台机器的管理员吗?您是从您的帐户运行它吗?
标签: c# filesystems iterator iteration loops