简体   繁体   中英

C# Streamwriter help

Hey guys I need a tad bit of help. I need my streamwriter to right out the file names i get from a Directory.Getfiles call

string lines = (listBox1.Items.ToString());
        string sourcefolder1 = textBox1.Text;
        string destinationfolder = (@"C:\annqcfiles");
        string[] files = Directory.GetFiles(sourcefolder1, lines + "*.ann");
        foreach (string listBoxItem in listBox1.Items)
        {
         Directory.GetFiles(sourcefolder1, listBoxItem + "*.txt");
         StreamWriter output = new StreamWriter(destinationfolder + "\\" + listBoxItem + ".txt");
        }

It creates the files perfectly it just doesnt add any content to the files. All i really want is the filename of the files it finds in the getfiles result.

Thanks in for any advice.

    foreach (string listBoxItem in listBox1.Items)
    {
     using (StreamWriter output = new StreamWriter(destinationfolder + "\\" + listBoxItem + ".txt"))
     {
           foreach (string fileName in Directory.GetFiles(sourcefolder1, listBoxItem + "*.txt"))
           {
                 output.WriteLine(fileName);
           }
     }
    }

Since GetFiles returns a string[] , don't use StreamWriter at all - just

File.WriteAllLines(path, files);

Where files is the string[] of paths to write, and path is the destination file.

Two things. Firstly you actually need to write the data to the StreamWriter, and secondly you need to make sure you close the StreamWriter so it actually gets flushed to the file.

Try this:

foreach (string listBoxItem in listBox1.Items)
{
    String[] filesInFolder Directory.GetFiles(sourcefolder1, listBoxItem + "*.txt");

    using(StreamWriter output = new StreamWriter(destinationfolder + "\\" + listBoxItem + ".txt"))
    {
        foreach(string filename in filesInFolder)
        {
            output.Write(filename);
        }
    }
}

The using statement ensures that the StreamWriter is closed when the execution passes out of the using block.

Alternatively, if this is all you are writing to the file, you could take a look at the Files.WriteAllLines(...) method.

You have to close your StreamWriter.

Or wrap your StreamWriter in a using statement, this will dispose and close your stream automatically.
The reason behind this is that your stream will keep your output in a buffer and only write it to a file when:
- a certain threshold is reached
- you call flush on it explicitly
- close or dispose the stream

You should wrap your streamwriter in a using statement, which will flush and close the streamwriter

using(StreamWriter output = new StreamWriter(destinationfolder + "\\" + listBoxItem + ".txt"))
{
    //Any code that writes in output
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM