简体   繁体   中英

Problem outputting text into a text file from c#

I am having problems getting the output of this event to go to a text file, I think it might be something to do with the "File" value

        private void button1_Click(object sender, EventArgs e)
        {

            var file = File.AppendText(@"c:\output.txt");

            StreamReader sr = new StreamReader(@"c:\filename.txt");
            Regex reg = new Regex(@"\w\:(.(?!\:))+");
            List<string> parsedStrings = new List<string>();
            while (sr.EndOfStream)
            {
                parsedStrings.Add(reg.Match(sr.ReadLine()).Value);
            }

        }
    }
}

File.AppendText(@"c:\output.txt"); returns a StreamWriter . I don't see where you are writing to this. You are just adding items to a List<String> . Looks like you forgot to call file.Write() call.

You don't need a List<String> in that case.

you can do

while (sr.EndOfStream)
{
    file.WriteLine(reg.Match(sr.ReadLine()).Value);
}

or if you need the List<String>

then you can try

parsedStrings.ForEach(s => file.WriteLine(s));

after the while loop.

Try something like:

using (StreamWriter sw = File.AppendText(@"c:\output.txt")) 
{
    StreamReader sr = new StreamReader(@"c:\filename.txt");
    Regex reg = new Regex(@"\w\:(.(?!\:))+");

    while (sr.EndOfStream)
        {
            sw.WriteLine(reg.Match(sr.ReadLine()).Value);
        }
}

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