我正在尝试学习 C#,因此,我观看教程并一步一步地按照它们进行操作,但我也喜欢在他们在教程中所做的程序中添加一些小东西。这次我在看关于文件流的newboston C#教程,我想创建一个可以读取字节和普通文本的文本阅读程序,所以我创建了3个按钮,2个用于选择阅读器应如何显示文本,1个用于打开文件对话框,但是当我选择该选项时,字节阅读器出现问题,它只显示零。
这就是我的程序的样子
这就是我的文本文件的样子
这就是选择字节选项时我的结果的样子
这是我的代码
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;
}
}
}
所以我不明白为什么程序显示为零,我的程序有什么问题以及如何改进它?谢谢你。