i am trying to learn C# so, i watch tutorials and follow them step by step, but i also like to add some small things to the programs they do in tutorials. this time i was watching thenewboston C# tutorial about file streaming, i want to create a text reading program which could both read byte-s and normal texts, so i created 3 buttons, 2 for choosing how the reader should show the text and 1 for opening file dialog, but something is wrong with byte reader when i choose that option it only show’s zeros.
this is how my program looks like
this is how my text file looks like
this is how my result looks like when choosing byte option
this is my code
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;
}
}
}
So i don’t understand why the program shows me zeros, what’s wrong with my program and how can i improve it?
thank you.
First
ReadToEndcall reaches to the end of stream, so nextsr.BaseStream.Readcall tries to read ahead of end of the file hence all zeros. You can either:text1to bytes instead of re-reading if you don’t care about the data loss during encoding.or
File.OpenReadoperation)Positionproperty.or