C# 如何循环、读取和写入文件夹和子文件夹文件

C# 如何循环、读取和写入文件夹和子文件夹文件,c#,C#,我在文件夹和子文件夹中写入文件时遇到问题 例如:-test是主文件夹 1) C:\测试\ 我想读写子文件夹文件 2) C:\test\12-05-2011\12-05-2011.txt 3) C:\test\13-05-2011\13-05-2011.txt 4) C:\test\14-05-2011\14-05-2011.txt 我的代码是: private void button1_Click(object sender, EventArgs e) { const string Pa

我在文件夹和子文件夹中写入文件时遇到问题

例如:-test是主文件夹

1) C:\测试\

我想读写子文件夹文件

2) C:\test\12-05-2011\12-05-2011.txt

3) C:\test\13-05-2011\13-05-2011.txt

4) C:\test\14-05-2011\14-05-2011.txt

我的代码是:

private void button1_Click(object sender, EventArgs e)
{
    const string Path1 = @"C:\test";
    DoOnSubfolders(Path1);

    try
    {
        StreamReader reader1 = File.OpenText(Path1);
        string str = reader1.ReadToEnd();
        reader1.Close();
        reader1.Dispose();
        File.Delete(Path1);
        string[] Strarray = str.Split(new char[] { Strings.ChrW(10) });
        int abc = Strarray.Length - 2;
        int xyz = 0;
        while (xyz <= abc)

}
private void按钮1\u单击(对象发送者,事件参数e)
{
常量字符串路径1=@“C:\test”;
DoOnSubfolders(路径1);
尝试
{

StreamReader reader1=File.OpenText(路径1); 字符串str=reader1.ReadToEnd(); reader1.Close(); reader1.Dispose(); 删除(路径1); string[]Strarray=str.Split(新字符[]{Strings.ChrW(10)}); int abc=直线长度-2; int xyz=0;
而(xyz您需要使用类目录信息和文件信息

DirectoryInfo d = new DirectoryInfo("c:\\test");
FileInfo [] fis = d.GetFiles();
DirectoryInfo [] ds = d.GetDirectories();

要以递归方式遍历子文件夹,您需要一个递归函数,即调用自身的函数。下面是一个足以让您使用的示例:

static void Main(string[] args)
{
    const string path = @"C:\temp\";
    DoOnSubfolders(path);
}

private static void DoOnSubfolders(string rootPath)
{
    DirectoryInfo d = new DirectoryInfo(rootPath);
    FileInfo[] fis = d.GetFiles();
    foreach (var fi in fis)
    {
        string str = File.ReadAllText(fi.FullName);
        //do your stuff
    }

    DirectoryInfo[] ds = d.GetDirectories();
    foreach (var info in ds)
    {
        DoOnSubfolders(info.FullName);
    }
}

首先看一下。秘诀是System.IO中的Directory.GetDirectories。

这里有一个快速的一行程序,可以将给定目录(以及所有子目录)中所有文本文件的内容写入控制台:

Directory.GetFiles(myDirectory,"*.txt*",SearchOption.AllDirectories)
       .ToList()
       .ForEach(a => Console.WriteLine(File.ReadAllText(a)));

首先,您可以通过调用并设置为
AllDirectories
来平坦递归调用

还有一个常见的错误(但您的问题并不清楚)是,在创建文件之前,需要创建一个目录。只需调用。并输入完整的路径(不带文件名)如果目录已经存在,它将不会自动执行任何操作,并且能够创建所需的整个结构。因此不需要检查或递归调用(如果您没有写访问权限,可能需要尝试捕获)

更新 下面是一个例子,它读入一个文件,在每一行上进行一些转换,然后将结果写入一个新文件。如果工作正常,原始文件将被转换后的文件替换

private static void ConvertFiles(string pathToSearchRecursive, string searchPattern)
{
    var dir = new DirectoryInfo(pathToSearchRecursive);

    if (!dir.Exists)
    {
        throw new ArgumentException("Directory doesn't exists: " + dir.ToString());
    }

    if (String.IsNullOrEmpty(searchPattern))
    {
        throw new ArgumentNullException("searchPattern");
    }

    foreach (var file in dir.GetFiles(searchPattern, SearchOption.AllDirectories))
    {
        var tempFile = Path.GetTempFileName();

        // Use the using statement to make sure file is closed at the end or on error.
        using (var reader = file.OpenText())
        using (var writer = new StreamWriter(tempFile))
        {
            string line;

            while (null != (line = reader.ReadLine()))
            {
                var split = line.Split((char)10);
                foreach (var item in split)
                {
                    writer.WriteLine(item);
                }
            }
        }

        // Replace the original file be the converted one (if needed)
        ////File.Copy(tempFile, file.FullName, true);
    }
}
在您的情况下,可以调用此函数

ConvertFiles(@"D:\test", "*.*")
您必须在c:\Test文件夹上配置(NTFS)安全性

通常,您会让应用程序在非管理员帐户下运行,因此运行该程序的帐户应该具有访问权限

如果您使用UAC在Vista或Windows 7上运行,您可能是管理员,但默认情况下不会使用管理(提升)权限

编辑

请看以下几行:

const string Path1 = @"C:\test";
DoOnSubfolders(Path1);
try
{
    StreamReader reader1 = File.OpenText(Path1);
最后一行试图读取文件夹“c:\test”,就像它是一个文本文件一样

你不能那样做。你想在那里实现什么?

此代码:

const string Path1 = @"C:\test";  
StreamReader reader1 = File.OpenText(Path1);
表示将“c:\test”作为文本文件打开…您得到的错误是:

Access to the path 'C:\test' is denied
您收到错误是因为如上所述,“c:\test”是一个文件夹。您不能像打开文本文件一样打开文件夹,因此出现错误

扩展名为
.txt
的文件的基本(全深度搜索)如下所示:

static void Main(string[] args) {
    ProcessDir(@"c:\test");
}


static void ProcessDir(string currentPath) {
    foreach (var file in Directory.GetFiles(currentPath, "*.txt")) {

        // Process each file (replace this with your code / function call /
        // change signature to allow a delegate to be passed in... etc
        // StreamReader reader1 = File.OpenText(file);  // etc

        Console.WriteLine("File: {0}", file);
    }

    // recurse (may not be necessary), call each subfolder to see 
    // if there's more hiding below
    foreach (var subFolder in Directory.GetDirectories(currentPath)) {
        ProcessDir(subFolder);
    }
}

那么,你是在提供文件夹列表,还是希望它递归地遍历你指定的文件夹的每个子文件夹?我希望递归地遍历文件夹的每个子文件夹从你的代码中不清楚你在哪里写出任何信息-鉴于这是失败的,这是一个相当重要的部分。你似乎没有e任何代码都可以在那里进行任何编写-您希望它编写什么?您是否尝试在Debugger中检查您的代码?我认为这是一个简单的错误,您可以通过Debugger轻松捕获它的读取,但它不会写入给定的路径const string Path1=@“C:\test\”doonsbfolders(Path1);但是发生了一个错误。错误是找不到路径“C:\test\”的一部分。是否可以将此代码添加到我的代码StreamReader reader1=File.OpenText(路径1);string str=reader1.ReadToEnd();reader1.Close();reader1.Dispose();File.Delete(路径1);string[]Strarray=str.Split(new char[]{Strings.ChrW(10)});int abc=Strarray.Length-2;int xyz=0;我正在使用XP3如何作为管理员运行您可以锁定导致异常的行吗?catch(exception){//在此情况下,错误是拒绝访问路径“C:\test”。}这是捕获,而不是导致异常的行。StreamReader reader1=File.OpenText(Path1);这是给出错误的行