Writing Binary file at certain address - c#

What I'm trying to do is read a blank file with no extension. From there, open the file and read it at a certain offset. Here's what I've done for that:
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Open 234cec File";
if (ofd.ShowDialog() == DialogResult.OK)
{
StreamReader sr = new StreamReader(File.OpenRead(ofd.FileName));
BinaryReader br = new BinaryReader(File.OpenRead(ofd.FileName));
string Texture1 = null;
for (int i = 0x2D670DE; i <= 0x2D6712F; i++)
{
br.BaseStream.Position = i;
Texture1 += br.ReadChar().ToString();
}
br.Close();
textBox1.Text = Texture1;
}
else
{
MessageBox.Show("Error");
}
}
The program works just fine and displays text in a textbox from what it read.
However, I want to be able to write back in the file, from what's in the textbox it read, with a Save button.
i.e. from what I modify in the textbox, then have it save back to my file (at the specified address) WITHOUT changing the file size (like replacing what's there).
The file I'm reading is a kinda big file like 120MB and it doesn't just contain text, it also contains other hex/code and such.
My problem is, I'm clueless as to what line I should do for my Save button after I modify what it read in the Textbox. Any help?

Related

c# wpf only 1 file gets selected

I created a WPF app in which I want to select many files from any given directory. The problem is that whenever I try to select multiple files, it will just copy the first file exactly as many times as many files I selected, instead of giving me all the different files.
What am I doing wrong?
TextFile textFile = new TextFile();
string[] arrAllFiles;
private void btnOpenFiles_Click(object sender, RoutedEventArgs e)
{
Stream myStream;
OpenFileDialog choofdlog = new OpenFileDialog();
choofdlog.Filter = "All Files (*.*)|*.*";
choofdlog.Multiselect = true;
if (choofdlog.ShowDialog() ==true)
{
//string sFileName = choofdlog.FileName;
arrAllFiles = choofdlog.FileNames; //used when Multiselect = true
}
//add all files in textbox
for (var i = 0; i < arrAllFiles.Length; i++)
{
textFile.files.Add(choofdlog);
myStream = textFile.files[i].OpenFile();
StreamReader reader = new StreamReader(myStream);
textFile.readFile.Add(reader);
lbFiles.Items.Add(arrAllFiles[i]);
}
}
i only use c# occasionally, so i can't give you a syntactical guarantee, but what i see at first glance is this
textFile.files.Add(choofdlog);
should be
textFile.files.Add(arrAllFiles[i]);
or
textFile.files.Add(choofdlog[i]);

Read textfile and show it in richtextbox. Show one word from Richtextbox in ComboBox then find it in text and replace it with TextBox.text

I have opened a .CSV file in RichTextBox.I added every line's first word to CombobBox items. I want to edit this a specific word and then save it back to the File.
This is how i open the file to richTextBox1.
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Csv files (.csv)|*.csv";
ofd.Title = "Open a file...";
if (ofd.ShowDialog() == DialogResult.OK)
{
StreamReader sr = new StreamReader(ofd.FileName);
richTextBox1.Text = sr.ReadToEnd();
}
Now i want a Button that finds my comboBox1.Text in richTextBox and replace it with txtbox.Text.
My button looks like this:
private void button1_Click(object sender, EventArgs e)
{
using (TextReader reader = new StringReader(richTextBox1.Text))
{
string str = reader.ReadToEnd();
string cbtxt = comboBox1.Text;
string tbtxt = txtbox.Text;
str = str.Replace(cbtxt, tbtxt);
}
}
I would add the method to the end of this button that would save back the text from richTextBox to my .CSV file but this replace method doesnt replace anything in my richTextBox.
My .CSV file (in richTextBox) looks like this:
somestring,somenumber,somespecialcharacters;
somestring2,somenumber2,somespecialcharacters2;
It has about 50 lines,and my combobox is filled with the first words of every line like: "somestring" "somestring2".
When i click on somestring (then its my combobox.text) then i write "newstring" to my txtbox.text. When i click my button it should find comboBox.text in richtxt and replace it with my txtbox.text.
Any ideas why it doesnt work?
You wrote:
but this replace method doesnt replace anything in my richTextBox.
This is because strings in C# are immutable? Whatever you do to strings, the original string is never changed. The result is always in a new string.
See Why .NET String is immutable?
So although your code changes the value of str, the original str that your richtextbox displays is not changed.
string str = reader.ReadToEnd();
string cbtxt = comboBox1.Text;
string tbtxt = txtbox.Text;
str = str.Replace(cbtxt, tbtxt);
str refers to a new string. RichTextBox1.Text still refers to the original string.
Solution: Assign the new string to the rich text box:
this.RichTextBox1.Text = str;
If you want to save the text in a file you'll have to create a FileWriter that will write the new string (not the changed string, strings can't change!).
Depending on how important it is that you don't lose the old file in case of problems, consider using a tmpfile to write, delete the original and move the tmpfile
In order to replace or delete something using a stream reader, you will need to delete every line and replace it with a new (temporary) file.
var tempFile = Path.GetTempFileName(); //Creates temporary file
List<string> linesToKeep = new List<string>(); //Creates list of all the lines you want to keep (everything but your selection)
using (FileStream fs = new FileStream(path(), FileMode.Open, FileAccess.Read)) //(this opens a new filestream (insert your path to your file there)
{
using (StreamReader sr = new StreamReader(fs)) //here is starts reading your file line by line.
{
while (!sr.EndOfStream) //as long it has not finished reading
{
string currentline = sr.ReadLine().ToString(); //this takes the current line it has been reading
string splitline = currentline; //this is a temporary string because you are going to have to split the lines (i think you have 3 so split in "," and then index the first line (your identifier or name)))
if (splitline.Split(';')[0] != ID) //split the line and add your personal identifier so it knows what to keep and what to delete.
{
linesToKeep.Add(currentline); //adds the line to the temporary file list of line that you want to keep
}
}
}
}
File.WriteAllLines(tempFile, linesToKeep); //writes all the lines you want to keep back into a file
File.Delete(path()); //deletes the old file
File.Move(tempFile, path()); //moves temporary file to old location of the old file.
On second notice, check out this code:
private void btnLoad_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == DialogResult.OK)
{
richTextBox1.LoadFile(ofd.FileName);
}
}
private void btnSave_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == DialogResult.OK)
{
richTextBox1.SaveFile(ofd.FileName);
}
}
I think this is more in line with what you had in mind?

How to save content from List<string> to a text file in C#?

I have a listbox that displays the names of the files that are opened either with a dragDrop functionality or with an OpenFileDialog, the file paths are stored in the List named playlist, and the listbox only displays the names without paths and extensions. When my form closes, the playlist content is saved to a .txt file. When I open again my application, the content in the text file is stored again in the listbox and the playlist. But when I add new files after re-opening the form, I don't know why it leaves a blank line between the last files and the recently added ones.
This is the code I use to WRITE the content of playlist(List) in the txt file:
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
if(listBox1.Items.Count > 0)
{
StreamWriter str = new StreamWriter(Application.StartupPath + "/Text.txt");
foreach (String s in playlist)
{
str.WriteLine(s);
}
str.Close();
}
This is the code used to READ the same txt file:
private void Form1_Load(object sender, EventArgs e) //Form Load!!!
{
FileInfo info = new FileInfo(Application.StartupPath + "/Text.txt");
if(info.Exists)
{
if (info.Length > 0)
{
System.IO.StreamReader reader = new System.IO.StreamReader(Application.StartupPath + "/Text.txt"); //StreamREADER
try
{
do
{
string currentRead = reader.ReadLine();
playlist.Add(currentRead);
listBox1.Items.Add(System.IO.Path.GetFileNameWithoutExtension(currentRead));
} while (true);
}
catch (Exception)
{
reader.Close();
listBox1.SelectedIndex = 0;
}
}
else
{
File.Delete(Application.StartupPath + "/Text.txt");
}
}
else
{
return;
}
}
The code used to add files to listbox and playlist:
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Select File(s)";
ofd.Filter = "Audio Files (*.mp3, *.wav, *.wma)|*.mp3|*.wav|*.wma";
ofd.InitialDirectory = "C:/";
ofd.RestoreDirectory = false;
ofd.Multiselect = true;
ofd.ShowDialog();
foreach (string s in ofd.FileNames)
{
listBox1.Items.Add(Path.GetFileNameWithoutExtension(s));
playlist.Add(s);
}
listBox1.SelectedIndex = 0;
This is what I get when I add new files after re-opening my form:
Thanks in advance, I hope StackOverflow community can help me!
First of all: debug your code and you'll find the problem yourself :)
Issue is the use of the WriteLine method. The last line you write should use the Write method instead so that you don't have an empty line at the end. Alternatively and easier to implement is to only add non-empty lines to your playlist such like this:
// ...
do
{
string currentRead = reader.ReadLine();
if (!string.IsNullOrWhiteSpace(currentRead)) // ignore empty lines
{
playlist.Add(currentRead);
listBox1.Items.Add(System.IO.Path.GetFileNameWithoutExtension(currentRead));
}
} while (true);
As a side comment: while (true) and using exception handling is a bad approach to end a loop.

Getting extra lines, but I don't know why

I am making a WPF program, and right now I want to be able to open and merge files. I have a button to open a file and I have a button to merge the file, and when I don't implement the "onTextChanged" method both buttons work properly and the files are formatted properly. But if I implement the onTextChanged method and use the merge file button, the previous 'file' gets extra lines in its output.
Open Button Code:
private void Button_Click_1(object sender, RoutedEventArgs e)
{
//Open windows explorer to find file
OpenFileDialog ofd = new OpenFileDialog();
ofd.CheckFileExists = true;
if (ofd.ShowDialog() ?? false)
{
//clears the buffer to open new file
buffer.Clear();
//string to hold line from file
string text;
// Read the file and add it line by line to buffer.
System.IO.StreamReader file =
new System.IO.StreamReader(ofd.FileName);
while ((text = file.ReadLine()) != null)
{
buffer.Add(text);
}
//close the open file
file.Close();
//write each element of buffer as a line in a temporary file
File.WriteAllLines("temp", buffer);
//open that temporary file
myEdit.Load("temp");
}
}
Merge Button Code:
private void merge_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.CheckFileExists = true;
if (ofd.ShowDialog() ?? false)
{
string text;
// Read the file and display it line by line.
System.IO.StreamReader file =
new System.IO.StreamReader(ofd.FileName);
while ((text = file.ReadLine()) != null)
{
buffer.Add(text); // myEdit.AppendText(text);
}
file.Close();
File.WriteAllLines("temp", buffer);
myEdit.Load("temp");
}
}
And when I execute this code, it adds lines in between the last 'file's output:
private void myEdit_TextChanged(object sender, EventArgs e)
{
tCheck.Stop();
tCheck.Start();
}
private void TimerEventProcessor(Object myObject, EventArgs myEventArgs)
{
tCheck.Stop();
Application.Current.Dispatcher.Invoke(new Action(() =>
{
buffer.Clear();
StringBuilder sb = new StringBuilder();
// pulls text from textbox
string bigS = myEdit.Text;
// getText();
for (int i = 0; i < (bigS.Length - 1); i++)
{
if (bigS[i] != '\r' && bigS[i + 1] != '\n')
{
sb.Append(bigS[i]);
}
else
{
buffer.Add(sb.ToString());
sb.Clear();
}
}
}));
}
If you are wondering why I don't use the Split method of a string, it is because I need to open 50+ MB text files and I get an out of memory exception upon using it. I really just want to keep formatting the same when I merge a file.
Wow this is a one line fix.
Original Line of Code:
buffer.Add(sb.ToString());
Changed (Correct) Line of Code:
buffer.Add(sb.ToString().Trim());
The changed worked, however if someone has any idea where these extra lines are coming from that would be helpful.

How to display an image from file system in a PictureBox in WinForm

I have a small doubt regarding loading an image in PictureBox in WinForms.
I want to show an image file from file system in a PictureBox on my form, say form1.
I am doing Windows applications using C#.
I want to check the file type also say is it pdf/text/png/gif/jpeg.
Is it possible to programmatically open a file from file system using C#?
If anyone knows please give any idea or sample code for doing this.
Modified Code: I have done like this for opening a file in my system, but I don't know how to attach the file and attach the file.
private void button1_Click(object sender, EventArgs e)
{
string filepath = #"D:\";
openFileDialog1.Filter = "Image Files (*.jpg)|*.jpg|(*.png)|*.png|(*.gif)|*.gif|(*.jpeg)|*.jpeg|";
openFileDialog1.CheckFileExists = true;
openFileDialog1.CheckPathExists = true;
if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
{
try
{
}
}
}
I don't know what I have to write in try block. Can anyone help on this?
Use Image.ImageFromFile http://msdn.microsoft.com/en-us/library/system.drawing.image.fromfile.aspx method
Image img = Image.ImageFromFile(openFileDialog1.FileName);
Should work.
EDIT
If you're going to set it to PictureBox, and what to see complete inside it, use picturebox
SizeMode property.
using System.IO;
openFileDialog1.FilterIndex = 1;
openFileDialog1.Multiselect = false; //not allow multiline selection at the file selection level
openFileDialog1.Title = "Open Data file"; //define the name of openfileDialog
openFileDialog1.InitialDirectory = #"Desktop"; //define the initial directory
if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
{
try
{
string filename = openFileDialog1.FileName;
FileStream fs=new FileStream(filename, FileMode.Open, FileAccess.Read); //set file stream
Byte[] bindata=new byte[Convert.ToInt32(fs.Length)];
fs.Read(bindata, 0, Convert.ToInt32(fs.Length));
MemoryStream stream = new MemoryStream(bindata);//load picture
stream.Position = 0;
pictureBox1.Image = Image.FromStream(stream);
}
}

Categories