C# 请问如何将数组内容输出到文本

cntcm 2007-11-10 10:49:22
总是菜菜的问题。。。
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();
}
}
}
}

但是输出到文本的时候总是只有最后一个比如本例中的就只输出“我是华人”。而不是能再控制台显示的所有内容。大虾指点哪。
...全文
1385 6 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
cntcm 2007-11-10
  • 打赏
  • 举报
回复
谢谢各位啦。。都试过了。都正确,boblaw指导的也很好。我记住了。分只有平分了。每人3分吧。。。谢谢了!
刚刚结贴时看见我只有16分了。这分怎么获取啊。我看了一下好像可以购买点卡。怎么买并且怎么用呢。有哪位愿意告诉一声吗?
-过客- 2007-11-10
  • 打赏
  • 举报
回复
List<string> arr = new List<string>();
arr.Add("我是小菜 ");
arr.Add("我是大虾 ");
arr.Add("我是华人 ");
using (StreamWriter sw = new StreamWriter(@"e:\lintest.txt"))
{
for (int i = 0; i < arr.Count; i++)
{
sw.WriteLine("Line" + arr[i]);
}
}
boblaw 2007-11-10
  • 打赏
  • 举报
回复
注意上面的代码,作为好的习惯,aFile也要应该释放资源.
boblaw 2007-11-10
  • 打赏
  • 举报
回复

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();
}

wangkun9999 2007-11-10
  • 打赏
  • 举报
回复
FileStream aFile = new FileStream( "lintest.txt ", FileMode.OpenOrCreate);
放在循环外面就可以了.

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();


-过客- 2007-11-10
  • 打赏
  • 举报
回复
FileStream aFile = new FileStream( "lintest.txt ", FileMode.OpenOrCreate); StreamWriter sw = new StreamWriter(aFile);
--->
StreamWriter sw = new StreamWriter("lintest.txt",true);

111,098

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧