C# 请问如何将数组内容输出到文本
总是菜菜的问题。。。
Baidu、Google跑了个遍,也没找到有C# 的数组内容输出到文本的代码。。不是VB,就是VC的。。菜了,看不明白啊。所以只有到这儿来发帖了。。
代码如下:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Collections;
namespace ConsoleApplication10
{
class Program
{
static void Main(string[] args)
{
int i = 0;
ArrayList arr= new ArrayList();
arr.Add("我是小菜");
arr.Add("我是大虾");
arr.Add("我是华人");
string text = "";
for (; i < arr.Count ; i++)
{
text = "Line" + (string)arr[i];
Console.WriteLine(text);
FileStream aFile = new FileStream("lintest.txt", FileMode.OpenOrCreate);
StreamWriter sw = new StreamWriter(aFile);
sw.Write(text);
sw.Close();
}
}
}
}
但是输出到文本的时候总是只有最后一个比如本例中的就只输出“我是华人”。而不是能再控制台显示的所有内容。大虾指点哪。
------解决方案--------------------FileStream aFile = new FileStream( "lintest.txt ", FileMode.OpenOrCreate); StreamWriter sw = new StreamWriter(aFile);
--->
StreamWriter sw = new StreamWriter("lintest.txt",true);
------解决方案-------------------- FileStream aFile = new FileStream( "lintest.txt ", FileMode.OpenOrCreate);
放在循环外面就可以了.
C# code
FileStream aFile = new FileStream( "lintest.txt ", FileMode.OpenOrCreate);
StreamWriter sw = new StreamWriter(aFile);
for (; i < arr.Count ; i++)
{
text = "Line " + (string)arr[i];
Console.WriteLine(text);
sw.Write(text);
}
sw.Close();
------解决方案--------------------
C# code
static void Main(string[] args)
{
int i = 0;
ArrayList arr = new ArrayList();
arr.Add("我是小菜 ");
arr.Add("我是大虾 ");
arr.Add("我是华人 ");
FileStream aFile = new FileStream("c:\\lintest.txt", FileMode.OpenOrCreate);
StreamWriter sw = new StreamWriter(aFile);
string text = " ";
for (; i < arr.Count; i++)
{
text = "Line " + (string)arr[i]+ Environment.NewLine;
Console.WriteLine(text);
sw.Write(text);
}
sw.Close();
aFile.Close();
aFile.Dispose();
}