简体   繁体   English

将Console.Writeline()语句的最终输出复制到文本文件和数组c#

[英]copy final output of Console.Writeline() statements to a text file and array c#

I'm using VS2013 and I'm new to programming. 我正在使用VS2013而且我是编程新手。 In my program I have Console.Writeline statements like below. 在我的程序中,我有如下的Console.Writeline语句。 Frequency is a double variable that outputs a peak values of frequencies in real-time. 频率是一个双变量,可实时输出频率峰值。

 if (Frequency > 328 && Frequency < 330)
 {                               
     Console.WriteLine(Frequency.ToString());
 }
 if (Frequency > 245 && Frequency < 247)
 {
     Console.WriteLine(Frequency.ToString());
 }
 if (Frequency > 195 && Frequency < 197)
 {
     Console.WriteLine(Frequency.ToString());
 }

Once I run the program, it outputs like this. 一旦我运行程序,它就像这样输出。

196.5654296875
246.9658203125
196.3984375
246.0322265625
196.5654296875
246.798828125
246.46484375
329.0322265625
329.0322265625
329.265625

I want to copy above whole final output numbers to a text file and to array also. 我想将上面的整个最终输出数字复制到文本文件和数组。 But I don't have any idea how to do this. 但我不知道该怎么做。 Please help me. 请帮我。

You can store it to a List<string> and have the same printed to a file like 您可以将它存储到List<string>并将其打印到文件中

 List<string> freq = new List<string>();

 if (Frequency > 328 && Frequency < 330)
 {                               
     Console.WriteLine(Frequency.ToString());
     freq.Add(Frequency.ToString());
 }

System.IO.File.WriteAllLines(@"D:\test\frequency_output.txt", freq.ToArray());

I would say the simplest way to do it, would be instantiate a writer that can write to file, and then call it's WriteLine() method similarlilly to console one, as such: 我想说最简单的方法就是实例化一个可写入文件的编写器,然后将其类似于控制台的WriteLine()方法调用,如下:

using (StreamWriter outfile = new StreamWriter("C:\numbers.txt"))
{
    if (Frequency > 328 && Frequency < 330)
    {                               
     Console.WriteLine(Frequency.ToString());
     outfile.WriteLine(Frequency.ToString());
    }
    if (Frequency > 245 && Frequency < 247)
    {
     Console.WriteLine(Frequency.ToString());
     outfile.WriteLine(Frequency.ToString());
    }
    if (Frequency > 195 && Frequency < 197)
    {
     Console.WriteLine(Frequency.ToString());
     outfile.WriteLine(Frequency.ToString());
    }   
}

You can find more on StreamWriter here: https://msdn.microsoft.com/pl-pl/library/System.IO.StreamWriter%28v=vs.110%29.aspx 您可以在此处找到有关StreamWriter的更多信息: https//msdn.microsoft.com/pl-pl/library/System.IO.StreamWriter%28v=vs.110%29.aspx

This is not very effective of course, however it should you get started. 当然这不是很有效,但是你应该开始吧。

There is whole lot of material on working with files in C#, so you should not have problems with finding help there as well. 在C#中使用文件有很多材料,所以你也不应该在那里找到帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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