How can I write those bytes in this case in C# - c#

I'm new in C#, And I have tried many solutions but couldn't do it, this is my code , How to write this four (bytes) declared in first method but I want write them to file in second method.
private void openfiles()
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Open";
ofd.Filter = "Bin files|*.bin";
if (ofd.ShowDialog() == DialogResult.OK)
{
string path = ofd.FileName;
using (BinaryReader b = new BinaryReader(File.Open(path, FileMode.Open)))
{
long size = new System.IO.FileInfo(path).Length;
long ssize = new System.IO.FileInfo(path).Length / 1024;
int allsize = unchecked((int)size);
byte[] bytes = b.ReadBytes(4);
}
}
}
private void button2_Click(object sender, EventArgs e)
{
using (BinaryWriter bw =new BinaryWriter(File.Open("FileName.bin",FileMode.Create)))
{
bw.Write(bytes);
bw.Close();
}
}

First you need to have somewhere to store the data after it is read and until it is written again. Best guess would be a field in the form, but that is design decision you need to make.
Next split up your code into functional parts, and don't put everything into button handlers. This way parts of the code can be re-used if needed.
Because the design intent is not clear, I have a very basic skeleton code below:
public partial class Form1 : Form
{
string _filename;
byte[] _data;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var dlg = new OpenFileDialog();
dlg.Title = "Open";
dlg.Filter = "Bin files|*.bin";
if (dlg.ShowDialog() == DialogResult.OK)
{
this._filename = dlg.FileName;
this._data = ReadHeader(_filename);
MessageBox.Show($"Read {_data.Length} bytes from {_filename}");
}
}
private void button2_Click(object sender, EventArgs e)
{
string destination = "Filename.bin";
if (MessageBox.Show($"About to overwrite {destination} with data from {_filename}. Proceed?", "File Header", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
WriteHeader(destination, this._data);
}
}
static byte[] ReadHeader(string filename)
{
byte[] fileHeader;
var fs = File.OpenRead(filename);
using (var fr = new BinaryReader(fs))
{
fileHeader = fr.ReadBytes(4);
}
fs.Close();
return fileHeader;
}
static void WriteHeader(string filename, byte[] fileHeader)
{
var fs = File.OpenWrite(filename);
using (var fw = new BinaryWriter(fs))
{
fw.Write(fileHeader);
}
fs.Close();
}
}

Related

Need help to rebuild the functions of the buttons, assign variable in c#

I am trying to build a small .pdf -> .txt / searchable .pdf converter, but I am having trouble to assign the first var result to the other buttons
Made myself a "solution" but the code seems too messed and exagerated.
using IronOcr;
using System;
using System.IO;
namespace ocr
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "pdf files (*.pdf)|*.pdf|All Files (*.*)|*.*";
if (ofd.ShowDialog() == DialogResult.OK)
{
textBox1.Text = ofd.FileName;
var Ocr = new IronTesseract(); // nothing to configure
IronOcr.License.LicenseKey = "SOMELICENSEKEY";
using (var Input = new OcrInput())
{
Input.AddPdf(ofd.FileName, "password");
var Result = Ocr.Read(Input);
Console.WriteLine(Result.Text);
richTextBox1.Text = Result.Text;
}
}
}
private void button2_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "pdf files (*.pdf)|*.pdf|All Files (*.*)|*.*";
if (ofd.ShowDialog() == DialogResult.OK)
{
textBox1.Text = ofd.FileName;
var Ocr = new IronTesseract(); // nothing to configure
IronOcr.License.LicenseKey = "SOMELICENSEKEY";
using (var Input = new OcrInput())
{
Input.AddPdf(ofd.FileName, "password");
var Result = Ocr.Read(Input);
Console.WriteLine(Result.Text);
Result.SaveAsTextFile("pdf.txt");
}
}
}
private void button3_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "pdf files (*.pdf)|*.pdf|All Files (*.*)|*.*";
if (ofd.ShowDialog() == DialogResult.OK)
{
textBox1.Text = ofd.FileName;
var Ocr = new IronTesseract(); // nothing to configure
IronOcr.License.LicenseKey = "SOMELICENSEKEY";
using (var Input = new OcrInput())
{
Input.AddPdf(ofd.FileName, "password");
var Result = Ocr.Read(Input);
Console.WriteLine(Result.Text);
Result.SaveAsSearchablePdf("pdfpesquisavel.pdf");
}
}
}
}
}
Tried to assign and use the variable "Result" in the others buttons fuctions (button 2 and button 3)
But it didn't worked.

C# and Ghostscript.net results in error (no picture)

I tried to create a little program to convert PDF to a TIF file using ghostscript but unfortunately it results in an error ("null"). Can't figure out why it's failing:
void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "PDF Files|*.pdf";
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
strfilename = openFileDialog1.FileName;
}
}
void button2_Click(object sender, EventArgs e)
{
FolderBrowserDialog targetfolder = new FolderBrowserDialog();
if (targetfolder.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
folder = targetfolder.SelectedPath;
}
}
void button3_Click(object sender, EventArgs e)
{
const string DLL_64BITS = "gsdll64.dll";
string NomeGhostscriptDLL;
NomeGhostscriptDLL = DLL_64BITS;
GhostscriptVersionInfo gvi = new GhostscriptVersionInfo(NomeGhostscriptDLL);
///var xDpi = 300;
var yDpi = 300;
using (var rasterizer = new GhostscriptRasterizer())
{
byte[] buffer = File.ReadAllBytes(strfilename);
MemoryStream ms = new MemoryStream(buffer);
rasterizer.Open(ms, gvi, true);
int PdfPages = rasterizer.PageCount;
for (int pageNumber = 1; pageNumber < rasterizer.PageCount; pageNumber++)
{
string outputTIFPath = Path.Combine(folder, "00" + pageNumber.ToString() + ".tiff");
Image pdf2TIF = rasterizer.GetPage(yDpi, pageNumber);
MessageBox.Show(outputTIFPath);
pdf2TIF.Save(outputTIFPath, ImageFormat.Tiff);
}
rasterizer.Close();
}
}
The error looks like this
Can anyone help me to sort this out?
try adding this
MyPlaceHolder.Controls.Add(pd2TIF);
below:
Image pdf2TIF = rasterizer.GetPage(yDpi, pageNumber);
I just read that on a different thread. im not 100% sure if it works

Winforms - Listbox will not update contenets until clicked

I'll try to add as much information as needed, please tell me if you need any extra info that I haven't added and I'll do my best to provide it.
The basics of my problem is that whenenver I press a button, it will grab the file I select and save it to a text file. This works fine and I can save as many files as needed. The problem lies in the listbox of my listbox. My app is a soundboard, and I want filenames with their hotkeys to be displayed on the listbox which almost works fine. On loading the application the listbox will take all saved files and display them accordingly once and on adding a file, the file will be added to the listbox and it will be saved. As I said this almost works because for some reason unknown to me, you have to click the listbox for it to add the content. My code is as follows:
public partial class Form1 : Form
{
public int getNumberOfSongs()
{
using (Stream stream = File.Open(#"Sounds.txt", FileMode.Open))
{
using (StreamReader reader = new StreamReader(stream))
{
string line = null;
for (int i = 0; i < 1; ++i)
{
line = reader.ReadLine();
int ine = Int32.Parse(line);
ine = ine + 1;
return ine;
}
}
}
return 8;
//This is only here so it doesn't give me an error, it is never used
}
public void fineChanger(string newText, string fileName, int line_to_edit)
{
string[] arrLine = File.ReadAllLines(fileName);
arrLine[line_to_edit] = newText;
File.WriteAllLines(fileName, arrLine);
}
public void addFile()
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.InitialDirectory = "c:\\";
openFileDialog.Filter = "WAV files (*.wav)|*.wav";
openFileDialog.DefaultExt = ".wav";
openFileDialog.FilterIndex = 2;
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
//Get the path of specified file
string filePath = openFileDialog.FileName;
songToAdd = filePath;
string control = filePath + "§modifier§hotkey";
string savePath = #"Sounds.txt";
int bruh = getNumberOfSongs();
fineChanger(control, savePath, bruh);
string bru = bruh.ToString();
fineChanger(bru, savePath, 0);
add = true;
}
}
public bool add = false;
public string songToAdd;
public bool load = true;
public Form1()
{
InitializeComponent();
}
public void button1_Click(object sender, EventArgs e)
{
addFile();
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (load == true)
{
listBox1.DataSource = File.ReadAllLines(#"Sounds.txt");
load = false;
}
if(add == true)
{
listBox1.Items.Add(songToAdd);
add = false;
}
}
}
P.S. I'm still a novice at windows forms and this app is still nowhere near done.
Instead of adding the items in SelectedIndexChanged I added them in outside. I load the saved songs in Form1_Load and I open/save the loaded files in the addFile() function.
Edited Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Media;
using System.Security.Cryptography.X509Certificates;
using System.Runtime;
using System.Runtime.InteropServices;
using Microsoft.VisualBasic;
using System.Diagnostics;
namespace SoundBoard
{
public partial class Form1 : Form
{
public int getNumberOfSongs()
{
using (Stream stream = File.Open(#"Sounds.txt", FileMode.Open))
{
using (StreamReader reader = new StreamReader(stream))
{
string line = null;
for (int i = 0; i < 1; ++i)
{
line = reader.ReadLine();
int ine = Int32.Parse(line);
ine = ine + 1;
return ine;
}
}
}
return 8;
//This is only here so it doesn't give me an error, it is never used
}
public bool load = true;
public void fineChanger(string newText, string fileName, int line_to_edit)
{
string[] arrLine = File.ReadAllLines(fileName);
arrLine[line_to_edit] = newText;
File.WriteAllLines(fileName, arrLine);
}
public void addFile()
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.InitialDirectory = "c:\\";
openFileDialog.Filter = "WAV files (*.wav)|*.wav";
openFileDialog.DefaultExt = ".wav";
openFileDialog.FilterIndex = 2;
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
//Get the path of specified file
string filePath = openFileDialog.FileName;
string control = filePath + "§modifier§hotkey";
string savePath = #"Sounds.txt";
int bruh = getNumberOfSongs();
fineChanger(control, savePath, bruh);
string bru = bruh.ToString();
fineChanger(bru, savePath, 0);
listBox1.Items.Add(filePath);
}
}
public bool loada = true;
public Form1()
{
InitializeComponent();
}
public void button1_Click(object sender, EventArgs e)
{
addFile();
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
if (loada == true)
{
listBox1.Items.Add(File.ReadAllLines(#"Sounds.txt"));
loada = false;
}
}
}
}

Promblemas to send to call my method to a button

I am learning to program in C # so my question is how to call the method from the button3
Look for information on the web but it is not very clear to me why I turn to this site
private void button3_Click_1(object sender, EventArgs e)
{
}
private void export2File(ListView lv, string splitter)
{
string filename = "";
SaveFileDialog sfd = new SaveFileDialog();
sfd.Title = "SaveFileDialog Export2File";
sfd.Filter = "Text File (.txt) | *.txt";
if (sfd.ShowDialog() == DialogResult.OK)
{
filename = sfd.FileName.ToString();
if (filename != "")
{
using (StreamWriter sw = new StreamWriter(filename))
{
foreach (ListViewItem item in lv.Items)
{
sw.WriteLine("{0}{1}{2}", item.SubItems[0].Text, splitter, item.SubItems[1].Text);
}
}
}
}
}
private void button3_Click_1(object sender, EventArgs e)
{
ListView listView1 = new ListView();
string splitter = ",";
export2File(listview1, splitter);
}
You need to pass a reference to the ListView on your Form, and the desired "splitter" into the method. Assuming listView1 and a comma:
private void button3_Click_1(object sender, EventArgs e)
{
export2File(listView1, ",");
}

how to pass file path to a variable using openfiledialog control?

I have this code here which i use in order to upload some stuff in a windows form:
public Form1()
{
InitializeComponent();
}
private void btnLoad_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
System.Windows.Forms.DialogResult dr = ofd.ShowDialog();
if (dr == DialogResult.OK)
{
userSelectedFilePath = ofd.FileName;
}
}
public string userSelectedFilePath
{
get
{ return tbFilePath.Text;
}
set
{tbFilePath.Text = value;
}
}
private void btn_compare_Click(object sender, EventArgs e)
{
string Xml1 = tbFilePath.Text;
string Xml2 = System.IO.File.ReadAllText(#"C:");
compare.comparison(Xml1, Xml2);
}
Apparently i'm doing something wrong because i'm not passing the tbFilePath.Text which i need when i have: string Xml1 = tbFilePath.Text;
What is it?
What you probably want is to compare the contents of 2 files.
As siride said your code does not make sense(see his comment)
Add this method to your class
private string FindFile()
{
OpenFileDialog ofd = new OpenFileDialog();
string _xmlPath1 = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
System.Windows.Forms.DialogResult dr = ofd.ShowDialog();
if (dr == DialogResult.OK)
return ofd.FileName;
else
return null;
}
And then you can do this:
private void btn_compare_Click(object sender, EventArgs e)
{
string x1 = System.IO.File.ReadAllText(FindFile(), Encoding.UTF8);
string x2 = System.IO.File.ReadAllText(FindFile(), Encoding.UTF8);
//Or if you already have the second file
//string x2 = System.IO.File.ReadAllText(#"C:\YourPath\someFileName.xml", Encoding.UTF8);
compare.comparison(x1, x2);
}

Categories

Resources