1

我编写了一个代码来读取文件夹中的所有文件,然后将它们写入文件。所有代码都符合并运行正常,但文件的文件名未显示在新文件中。

代码:

private void Form1_Load(object sender, EventArgs e)
{
    DialogResult result = folderBrowserDialog1.ShowDialog(); // Show the dialog.
    // create a list to insert the data into
    //put all the files in the root directory into array
    string[] array1 = Directory.GetFiles(@"C:\Users\a3708906\Documents\Filereader m 15062012", "*.csv");

    // Display all files.
    TextWriter tw1 = new StreamWriter("C:/Users/a3708906/Documents/Filereader m 15062012/Filereader m 15062012/listoffiles.txt");
    List<string> filenames = new List<string>();
    tw1.WriteLine("--- Files: ---");
    foreach (string name in array1)
    {
            tw1.WriteLine(name);
    }
    tw1.Close();
}

我会很感激你的帮助。

4

6 回答 6

1

您不厌其烦地询问用户文件夹位置,但您没有检索该文件夹位置。代码应该是

    string[] array1 = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.csv");

    // Display all files.
    TextWriter tw1 = new StreamWriter(folderBrowserDialog1.SelectedPath+"/listoffiles.txt");
于 2012-06-15T11:25:57.123 回答
0

我会说你的文件夹路径中的“空间”把事情搞砸了。按照msdn中的说明尝试转义“空白”

于 2012-06-15T11:27:10.820 回答
0

If the file isn't created (ie its just not there, even if it's just blank) then you problem lies with the stream writer. If this is the case I would suggest changing the direction of slashes so that your path is

TextWriter tw1 = new StreamWriter("C:\\Users\\a370890\\Documents\\Filereader m 15062012\\Filereader m 15062012\\listoffiles.txt");

If the file is created but nothing is written have a look at the flush command.

tw1.Flush();
于 2012-06-15T11:19:45.110 回答
0

Set a breakpoint to verify that GetFiles is returning files.

(Consider renaming array1 to something more meaningful)

Set a breakpoint on tw1.WriteLine(name) and ensure it is being hit.

It should be pretty easy to see the problem. My guess is that you simply aren't getting any files returned from GetFiles, but the breakpoints will tell you for sure. If your output file is created but missing the files - this is most likely the case.

If your output file doesn't exist; take a closer look at your file writing code.

于 2012-06-15T11:20:06.410 回答
0

I think problem is with your file path or file writing capability.

You use folderbrowserdialog but do not use it to get selected file name. Instead you give path manually. also your output path can have problem.

于 2012-06-15T11:20:08.300 回答
0

尝试这个 :

using(system.IO.StreamWriter tw1 = 
      new system.IO.StreamWriter(@"C:/Users/a3708906/Documents/Filereader m 15062012/Filereader m 15062012/listoffiles.txt")
{
    foreach (string name in array1)
    {
        tw1.WriteLine(name);
    }
}
于 2018-12-24T04:21:55.203 回答