如何读取一个字节流byte[]生成txt文件?

ansel13 2009-07-19 07:21:00
我在做一些web的设计,功能之一是要在网页上上传txt文件,然后服务器端读取它生成一个字节流,然后调用一个WebService把这个字节流变成txt文件,并对这个文件按照固定格式读取部分数据,并生成一个XML文件。

我的最终目的是得写入了所需数据的XML文件。

现在碰到的难题是:如何把我所得到的字节流变成txt文件?

我可以用下面的代码对一个实际存在、有文件路径的文件进行按行读取:
string strLine = "";
StreamReader sr = new StreamReader("文件路径");
ArrayList al = new ArrayList();
while (strLine != null)
{
strLine = sr.ReadLine();
al.Add(strLine);
}


然后在下面的代码中,我已经得到了字节流,但只能把这个字节流解码后放进到字符串变量中。可是怎么做才能把字节流解码了写入一个txt文本中呢?而这个txt文本文件我又不需要真正生成后保存在服务器硬盘上,我只是想使用readline()来读取其中的数据。


//上传按钮触发事件,读取txt并显示内容到textbox1中
protected void Button1_Click(object sender, EventArgs e)
{
//获取完整长文件名(短文件名+扩展名)
string fileName = this.FileUpload1.PostedFile.FileName.ToString();

//上传文件的大小(byte)
int fileLength = this.FileUpload1.PostedFile.ContentLength;

//获取文件的短文件名
string frontFileName = Path.GetFileNameWithoutExtension(this.FileUpload1.PostedFile.FileName);

//获取文件的扩展名
string fileExt = fileName.Substring(fileName.LastIndexOf("."));

//重新设置一个新的完整长文件名,格式为:短文件名+上传时间+扩展名
fileName = "\\" + frontFileName + DateTime.Now.ToString("yyyyMMddhhmmss") + fileExt;


//使用新文件名将文件保存到服务器的项目文件夹upload中
try
{
//文件保存
FileUpload1.PostedFile.SaveAs(HttpRuntime.AppDomainAppPath + @"\upload\" + fileName);
string fileurl = HttpRuntime.AppDomainAppPath + @"\upload\" + fileName;
Response.Write("文件上传成功");

//读取文件,获得字节流
FileStream fs = new FileStream(fileurl, FileMode.Open);
long i = fs.Length;
byte[] b = new byte[i];
fs.Read(b, 0, Convert.ToInt32(b.Length)); //得到所要的字节流b
UTF8Encoding temp = new UTF8Encoding(true);
string data = temp.GetString(b);//字节流被解码并放入到一个字符串中
fs.Close();


}
catch (Exception exc)
{
Response.Write("文件上传错误,原因:"+exc.ToString());
}
...全文
1955 17 打赏 收藏 转发到动态 举报
写回复
用AI写文章
17 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhaodelizhaodeli 2012-06-11
  • 打赏
  • 举报
回复
谁能告诉我怎么把listview数据导入PDF中
zhaodelizhaodeli 2012-06-11
  • 打赏
  • 举报
回复
谁能告诉我怎么把listview数据导入PDF中
yang1216 2009-07-19
  • 打赏
  • 举报
回复
实在不行了,就先生成一个tmp.txt,用完了就删除。
ansel13 2009-07-19
  • 打赏
  • 举报
回复
我是调用WebService来对字节流进行处理(转换为txt,然后读取txt)
[Quote=引用 13 楼 wowoj2ee 的回复:]
Stream stream = fileUpload.InputStream;
StreamReader streamReader = new StreamReader(stream);

string line = streamReader.ReadLine();
[/Quote]
wowoj2ee 2009-07-19
  • 打赏
  • 举报
回复
Stream stream = fileUpload.InputStream;
StreamReader streamReader = new StreamReader(stream);

string line = streamReader.ReadLine();
ansel13 2009-07-19
  • 打赏
  • 举报
回复
问题补充:


谢谢楼上各位,总结了一下,在我一楼的代码后面又写了下面代码:

FileStream aFile = new FileStream("Temp.txt", FileMode.Create);

aFile.Seek(0, SeekOrigin.Begin);
aFile.Write(b, 0, b.Length); //将字节数据写入文件


string strLine = "";
StreamReader sr = new StreamReader(aFile);
ArrayList al = new ArrayList();
while (strLine != null)
{
strLine = sr.ReadLine();
al.Add(strLine); //把aFile里面的数据按行读取到一个ArrayList中
}

不知道可行否?

我不是windows窗体程序,无法用下面代码验证
foreach (string temp in al)
{
Console.WriteLine(temp);
}


弄了一个通宵了,现在脑子晕了,我怎么验证我所得到的数组al里面的确按行存储了txt文件的内容?
ansel13 2009-07-19
  • 打赏
  • 举报
回复
能详细一点吗?谢谢你了。
path是txt文件的路径吗?但是这个文件还没有生成啊,我不知道如何通过字节流来生成一个txt,而且我希望它最好不要生成到硬盘中。



[Quote=引用 2 楼 hbxtlhx 的回复:]
1:
System.IO.File.WriteAllBytes(path, bytes);

2:
System.IO.FileStream f = new System.IO.FileStream(path, System.IO.FileMode.Create);
f.Write(Array, offset, count);

[/Quote]
zhouzangood 2009-07-19
  • 打赏
  • 举报
回复
路过顶顶
ansel13 2009-07-19
  • 打赏
  • 举报
回复
因为要求是服务器调用WebService来根据字节流生成txt文件,并对txt文件进行某种固定格式的读取操作,最后得到XML文件返回给服务器,所以我个人觉得WebService处理字节流时生成的txt文件不需要再保存了。

具体怎么实现呢?内存流 MemoryStream。。。。我得慢慢去研究了

[Quote=引用 6 楼 cstod 的回复:]
而这个txt文本文件我又不需要真正生成后保存在服务器硬盘上,我只是想使用readline()来读取其中的数据。

===>

内存流 MemoryStream

读取的时候用文本流包装一下
[/Quote]
ansel13 2009-07-19
  • 打赏
  • 举报
回复
我在尝试使用你代码里面的aFile.Write(byData, 0, byData.Length);来把我的字节流写入aFile,但是怎么来按行读取呢?

[Quote=引用 1 楼 qqiuzaihui 的回复:]
      static void Main(string[] args)
      {
        byte[] byData;
        char[] charData;

        try
        {
            FileStream aFile = new FileStream("Temp.txt", FileMode.Create);        //创建新文件,若存在原文件则先删除。
            charData = "My pink half of the drainpipe.".ToCharArray();              //创建字符数组
            byData = new byte[charData.Length];
            Encoder e = Encoding.UTF8.GetEncoder();                                //基于UTF8编码模式创建Encoder对象,即Unicode编码模式
            e.GetBytes(charData, 0, charData.Length, byData, 0, true);              //将字符数组并转换为字节数据

            // Move file pointer to beginning of file
            aFile.Seek(0, SeekOrigin.Begin);
            aFile.Write(byData, 0, byData.Length);                                  //将字节数据写入文件
        }
        catch (IOException ex)
        {
            Console.WriteLine("An IO exception has been thrown!");
            Console.WriteLine(ex.ToString());
            Console.ReadKey();
            return;
        }
[/Quote]
CsToD 2009-07-19
  • 打赏
  • 举报
回复
而这个txt文本文件我又不需要真正生成后保存在服务器硬盘上,我只是想使用readline()来读取其中的数据。

===>

内存流 MemoryStream

读取的时候用文本流包装一下
qicai841125 2009-07-19
  • 打赏
  • 举报
回复
路过
wuyq11 2009-07-19
  • 打赏
  • 举报
回复
以字符串的形式取得文本文件的内容ReadAllText(String path, Encoding encoding)
以字节数组的形式取得文件的内容ReadAllBytes(String path)

WriteAllBytes(string path, byte[] bytes);
WriteAllLines(string path, string[] contents, Encoding encoding);
WriteAllText(string path, string contents, Encoding encoding);


FileStream fsMyfile = new FileStream("test.txt" , FileMode.Create, FileAccess.ReadWrite);
StreamWriter swMyfile = new StreamWriter(fsMyfile);
swMyfile.WriteLine("Hello");
swMyfile.Flush();
StreamReader srMyfile= new StreamReader(fsMyfile);
srMyfile.BaseStream.Seek(0, SeekOrigin.Begin);
Console.WriteLine("以文本方式读文件");
string s1;
while((s1 = srMyfile.ReadLine())!=null)
{
Console.WriteLine(s1);
}
Console.WriteLine();
BinaryReader brMyfile= new BinaryReader (fsMyfile);
brMyfile.BaseStream.Seek(0, SeekOrigin.Begin);
Console.WriteLine("****************以二进制方式读文件*********************");
Byte b1;
while(brMyfile.PeekChar()>-1)
{
b1=brMyfile.ReadByte();
if(b1 != 13 && b1 != 10)
{
Console.Write("{0}",b1.ToString());
Console.Write(".");
}
else
{
Console.WriteLine();
}
}
brMyfile.Close();
srMyfile.Close();
fsMyfile.Close();

tthh_0013 2009-07-19
  • 打赏
  • 举报
回复
ding...
北京的雾霾天 2009-07-19
  • 打赏
  • 举报
回复
1:
System.IO.File.WriteAllBytes(path, bytes);

2:
System.IO.FileStream f = new System.IO.FileStream(path, System.IO.FileMode.Create);
f.Write(Array, offset, count);
qqiuzaihui 2009-07-19
  • 打赏
  • 举报
回复
static void Main(string[] args)
{
byte[] byData;
char[] charData;

try
{
FileStream aFile = new FileStream("Temp.txt", FileMode.Create); //创建新文件,若存在原文件则先删除。
charData = "My pink half of the drainpipe.".ToCharArray(); //创建字符数组
byData = new byte[charData.Length];
Encoder e = Encoding.UTF8.GetEncoder(); //基于UTF8编码模式创建Encoder对象,即Unicode编码模式
e.GetBytes(charData, 0, charData.Length, byData, 0, true); //将字符数组并转换为字节数据

// Move file pointer to beginning of file
aFile.Seek(0, SeekOrigin.Begin);
aFile.Write(byData, 0, byData.Length); //将字节数据写入文件
}
catch (IOException ex)
{
Console.WriteLine("An IO exception has been thrown!");
Console.WriteLine(ex.ToString());
Console.ReadKey();
return;
}

110,536

社区成员

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

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

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