2013-04-03 60 views
0

我有一个浮点数的数组,它具有未知长度,因为数组是动态的(随着新数据的添加,它会增长)。我需要找到一种方法将数据存储到文本文件中。将双数组保存到文本文件c#

我想将文本文件格式化为每行有一个浮点数。

我一直在寻找网络,但找不到解决方案,我是c#的新手,所以如果有人能指出我解决问题的正确方向,我将非常感激。

+2

'我一直在网上搜索,但找不到解决方案'难以置信。 – I4V

+3

在附注中,“列表”可能更适合您的点数增长。 (调整数组的大小相对昂贵) – keyboardP

回答

23

你可以做一个单一的线在.NET 4.0中,像这样:

File.WriteAllLines(
    @"c:\data\myfile.txt" // <<== Put the file name here 
, myDoubles.Select(d => d.ToString()) 
); 
3
using(StreamWriter sr = new StreamWriter("filename.txt")) 
{ 
    foreach(var item in myArray) 
    { 
     sr.WriteLine(item); 
    } 
} 

不要忘记使用(使用System.IO)将需要添加

+0

我没有意识到这很简单,我的Google搜索技巧需要一些工作。 –

0

东西像这样:

public class Program 
{ 
    static void Main(string[] args) 
    { 
     double[] values = { 0.0, 1.0, 2.0 }; 

     using (StreamWriter writer = new StreamWriter(@"C:\out.txt")) 
     { 
      foreach (var value in values) 
      { 
       writer.WriteLine(value); 
      } 
     } 
    } 
} 
+1

你为什么重复“尼古拉·科斯托夫”的答案? – I4V