简单的文件流程序,有什么不对?如何提高?

时间:2012-06-03 09:18:42

标签: c# .net filestream

我正在努力学习C#所以,我会一步一步地观看教程并按照它们进行操作,但我也想在教程中为程序添加一些小东西。这次我正在观看有关文件流的newboston C#教程,我想创建一个文本阅读程序,它可以读取字节和普通文本,所以我创建了3个按钮,2个用于选择阅读器应如何显示文本,1个用于打开文件对话框,但是当我选择该选项时它只显示零的字节阅读器有问题。

这就是我的程序看起来像my program

的方式

这就是我的文本文件看起来像my text file

的方式

这是我在选择字节选项enter image description here

时的结果

这是我的代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Media;
using System.IO;

namespace sound
{
    public partial class Form1 : Form
    {
    bool bytebuttonclicked = false;
    bool normalbuttonclicked = false;
    string text1;
    public Form1()
    {
        InitializeComponent();
    }
    SoundPlayer My_JukeBox = new SoundPlayer(@"C:\WINDOWS\Media\tada.wav");

    private void button1_Click(object sender, EventArgs e)
    {
        OpenFileDialog OFD = new OpenFileDialog();

        if (OFD.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            StreamReader sr = new StreamReader(File.OpenRead(OFD.FileName));
            if (normalbuttonclicked == true && bytebuttonclicked == false)
            {
                textBox1.Text = sr.ReadToEnd();
                sr.Dispose();
            }
            else if (bytebuttonclicked == true && normalbuttonclicked == false)
            {
                text1 = sr.ReadToEnd();
                byte[] Buffer = new byte[text1.Length];
                sr.BaseStream.Read(Buffer, 0, text1.Length);
                foreach (byte MyByte in Buffer)
                    textBox1.Text += MyByte.ToString("X") + " ";
                sr.Dispose();
            }
            else
            {
                MessageBox.Show("choose one button");
            }
        }
        My_JukeBox.Play();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        bytebuttonclicked = true;
        button1.Enabled = true;
    }

    private void button3_Click(object sender, EventArgs e)
    {
        normalbuttonclicked = true;
        button1.Enabled = true;
    }
}
}

所以我不明白为什么程序会显示零,我的程序出了什么问题以及如何改进它? 谢谢。

2 个答案:

答案 0 :(得分:1)

第一个ReadToEnd调用到达流的末尾,因此下一个sr.BaseStream.Read调用会尝试在文件末尾之前读取,因此全部为零。你可以:

  • 如果您不关心编码过程中的数据丢失,请将已读取text1转换为字节而不是重新读取。

  • 通过设置流(File.OpenRead操作的结果)Position属性来重置流(而不是阅读器)的位置。

  • 重新打开流。

答案 1 :(得分:1)

回应ssg的回答和vato的评论。

ssg表示将text1转换为Byte[]而不是读取文件末尾。

替换这些行:

byte[] Buffer = new byte[text1.Length];
sr.BaseStream.Read(Buffer, 0, text1.Length);

有了这个:

byte[] Buffer = Encoding.UTF8.GetBytes(text1);

这将创建一个名为byte[]的{​​{1}},其中包含Buffer byte[]

text1会将Encoding.UTF8.GetBytes(text1)转换为text1

希望这有帮助!