MD5 Comparison not working [duplicate] - c#

This question already has answers here:
Calculate MD5 checksum for a file
(7 answers)
Comparing two byte arrays in .NET
(28 answers)
Closed 6 years ago.
I tried to create a simple little application to make it easier to create the Update files for my main project, by just comparing files in two more or less similar folders and telling me what files are different. But it always gives me the following output when testing two completely similar folders:
C:\Users\there\Desktop\Folder 2\1.txt
C:\Users\there\Desktop\Folder 2\2.txt
My code:
private void FirstFolderBtn_Click(object sender, EventArgs e)
{
using (var fbd = new FolderBrowserDialog())
{
DialogResult result = fbd.ShowDialog();
if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
{
FirstFolderTB.Text = fbd.SelectedPath;
}
}
}
private void SecondFolderButton_Click(object sender, EventArgs e)
{
using (var fbd = new FolderBrowserDialog())
{
DialogResult result = fbd.ShowDialog();
if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
{
SecondFolderTB.Text = fbd.SelectedPath;
}
}
}
private void CompareBtn_Click(object sender, EventArgs e)
{
foreach(string file in Directory.GetFiles(FirstFolderTB.Text))
{
byte[] storedFileHash;
using (var md5 = MD5.Create())
{
using (var stream = File.OpenRead(file))
{
storedFileHash = md5.ComputeHash(stream);
}
using (var stream = File.OpenRead(file.Replace(FirstFolderTB.Text, SecondFolderTB.Text)))
{
if(storedFileHash != md5.ComputeHash(stream))
{
ResultTB.AppendText(file.Replace(FirstFolderTB.Text, SecondFolderTB.Text) + "\n");
}
}
}
}
}
I think I am just being dumb right now and overseeing some dumb mistake but I would appreciate if someone could help.
Thanks, Jan

Your bytes comparison is wrong
storedFileHash != md5.ComputeHash(stream)
this will compare references not the bytes.
Use SequenceEqual:
if (storedFileHash.SequenceEqual(md5.ComputeHash(stream)) == false) {
ResultTB.AppendText(file.Replace(FirstFolderTB.Text, SecondFolderTB.Text) + "\n");
}
if missing add using System.Linq in the using section

Related

C# high score in game [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Bassicaly I'm stucked with displaying high scores via listbox by discending order(like 500 to 1). Here is my code, keep in mind that label1 is score in the game, so if anyone may help me please?
{
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}
private void Form3_Load(object sender, EventArgs e)
{
label1.Text = Form2.passingText;
StreamWriter q = new StreamWriter("C:\\Users\\BS\\Desktop\\tex.txt", true);
q.WriteLine(label1.Text);
q.Close();
StreamReader sr = new StreamReader("C:\\Users\\BS\\Desktop\\tex.txt");
string g = sr.ReadLine();
while (g != null)
{
listBox1.Items.Add(g);
g = sr.ReadLine();
}
sr.Close();
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
You can read file as list of lines and then sort it using Linq
So, instead of using SteamReader, try this:
using System.Linq;
//....
List<string> hiscores = File.ReadAllLines("C:\\Users\\BS\\Desktop\\tex.txt").ToList();
hiscores.Sort();
foreach (string s in hiscores)
listBox1.Items.Add(s);
EDIT:
since you have to use StreamReader, here is this approach (but the principle is same):
List<string> hiscores = new List<string>();
StreamReader sr = new StreamReader("C:\\Users\\BS\\Desktop\\tex.txt");
string g = sr.ReadLine();
while (g != null)
{
hiscores.Add(g);
g = sr.ReadLine();
}
sr.Close();
hiscores.Sort();
hiscores.Reverse();
//alternatively, instead of Sort and then reverse, you can do
//hiscores.OrderByDescending(x => x);
foreach(string s in hiscores)
{
listBox1.Items.Add(s);
}

C# directory search (the number) [duplicate]

This question already has answers here:
Number of folder inside a directory
(3 answers)
Closed 7 years ago.
private int dReturn, fReturn = 0;
public Maker()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (fd.ShowDialog() != DialogResult.OK) { return; }
listView1.Items.Clear();
dReturn = 0;
fReturn = 0;
textBox1.Text = fd.SelectedPath;
Scanner scanner = new Scanner();
scanner.Show();
fscan(fd.SelectedPath);
dscan(fd.SelectedPath);
scanner.Close();
MessageBox.Show("File : " + fReturn + ", Folder : " + dReturn, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private int dscan(string path)
{
try
{
foreach (string d in Directory.GetDirectories(path))
{
dReturn = dReturn + 1;
dscan(d);
Application.DoEvents();
}
}
catch(Exception)
{
ListViewItem access = new ListViewItem(path);
listView1.Items.Add(access);
}
return dReturn;
}
I want know number of folders in selected path.
So I made a recursive function as above.
But The number of folders not the same as PC property view.
Please Help me...
Fine when the path is small, the problem arises when large.
Thanks for your comment.
Sorry, It was Not enough description.
I show you some image.
enter image description here
like this my program search more number of folder.
Maybe you have some hidden folders (C# - Get a list of files excluding those that are hidden) ?
By the way, GetDirectories can return all subdirectories : https://msdn.microsoft.com/fr-fr/library/ms143314(v=vs.110).aspx :
Directory.GetDirectories(path, "*", SearchOption.AllDirectories);
If you still have problems, try debugging to see the differences.

Why does IrfanView say my jpg file is a png file?

My utility is supposed to resize either .jpg or .png files.
It seems to work fine in one location (at work, where I don't have IrfanView installed). But at home, when I open a *.jpg and then save it (resized), I see:
However, the image still displays fine in either case (whether I select "Yes" or "No" in the dialog.
IOW, I'm able to load and save both jpgs and pngs, and they save as such, and display fine. But IrfanView claims they are messed up.
Actually, I'm not sure how the image is saved; I was assuming it just saved it in the proper format "behind the scenes" based on the extension. Anyway, as this is a rather simple utility, I will just show all the code:
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
namespace FileResizingUtil
{
public partial class FormFileResizer : Form
{
private Image _imgToResize;
String _originalFilename = String.Empty;
public FormFileResizer()
{
InitializeComponent();
}
private void buttonChooseImage_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog
{
InitialDirectory = "c:\\",
Filter = "JPG files (*.jpg)|*.jpg| PNG files (*.png)|*.png", FilterIndex = 2, RestoreDirectory = true
};
if (ofd.ShowDialog() == DialogResult.OK)
{
try
{
_originalFilename = ofd.FileName;
_imgToResize = Image.FromFile(_originalFilename);
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
// If made it to here, it must be good
String preamble = labelImgSelected.Text;
labelImgSelected.Text = String.Format("{0}{1}", preamble, _originalFilename);
textBoxOrigHeight.Text = _imgToResize.Height.ToString();
textBoxOrigWidth.Text = _imgToResize.Width.ToString();
buttonApplyPercentageChange.Enabled = true;
//buttonResizeImage.Enabled = true;
}
private void buttonResizeImage_Click(object sender, EventArgs e)
{
// Really large images take awhile, so show an hourglass
Cursor.Current = Cursors.WaitCursor;
try
{
var size = new Size { Height = Convert.ToInt32(textBoxNewHeight.Text), Width = int.Parse(textBoxNewWidth.Text) };
// Two different ways of getting the int val
Image resizedImg = FileResizeUtils.GetResizedImage(_imgToResize, size);
String fileNameSansExtension = Path.GetFileNameWithoutExtension(_originalFilename);
String fileNameExtension = Path.GetExtension(_originalFilename);
String newFilename = String.Format("{0}{1}_{2}{3}", fileNameSansExtension, size.Height, size.Width, fileNameExtension);
// If used a different extension (jpg where the original was png, or vice versa) would the Save be intelligent enough to actually save in the other format?
resizedImg.Save(newFilename);
MessageBox.Show(String.Format("Done! File saved as {0}", newFilename));
Recycle();
}
finally
{
Cursor.Current = Cursors.Default;
}
}
private void Recycle()
{
buttonResizeImage.Enabled = false;
buttonApplyPercentageChange.Enabled = false;
labelImgSelected.Text = "Image selected: ";
textBoxOrigHeight.Text = String.Empty;
textBoxOrigWidth.Text = String.Empty;
// Retain the percentage vals, as it may be that all in a batch need to be the same pair of vals
}
private void buttonApplyPercentageChange_Click(object sender, EventArgs e)
{
int origHeight = _imgToResize.Height;
int origWidth = _imgToResize.Width;
// Two ways to convert the val
double heightFactor = (double)numericUpDownHeight.Value / 100.0;
double widthFactor = Convert.ToDouble(numericUpDownWidth.Value) / 100.0;
if (heightFactor < 0 || widthFactor < 0)
{
// show an error - no negative values allowed- using updown, so that should not be possible
}
var newHeight = Convert.ToInt32(origHeight * heightFactor);
var newWidth = Convert.ToInt32(origWidth * widthFactor);
textBoxNewHeight.Text = newHeight.ToString();
textBoxNewWidth.Text = newWidth.ToString();
buttonResizeImage.Enabled = true;
}
private void textBoxNewHeight_TextChanged(object sender, EventArgs e)
{
EnableResizeButtonIfValidDimensionsEntered();
}
private void EnableResizeButtonIfValidDimensionsEntered()
{
if (String.IsNullOrWhiteSpace(textBoxOrigHeight.Text)) return;
String candidateHeight = textBoxNewHeight.Text;
String candidateWidth = textBoxNewWidth.Text;
int validHeight;
int validWidth;
buttonResizeImage.Enabled = (int.TryParse(candidateHeight, out validHeight)) &&
(int.TryParse(candidateWidth, out validWidth));
}
private void numericUpDownHeight_ValueChanged(object sender, EventArgs e)
{
if (checkBoxRetainRatio.Checked)
{
numericUpDownWidth.Value = numericUpDownHeight.Value;
}
}
private void numericUpDownWidth_ValueChanged(object sender, EventArgs e)
{
if (checkBoxRetainRatio.Checked)
{
numericUpDownHeight.Value = numericUpDownWidth.Value;
}
}
}
}
..and the GUI (just prior to hitting the "Resize Image" button:
UPDATE
Based on Eugene Sh.'ls comment, I changed my Save method to the following block:
bool success = true;
. . .
if (fileNameExtension != null && fileNameExtension.ToLower().Contains("jpg"))
{
resizedImg.Save(newFilename, ImageFormat.Jpeg);
}
else if (fileNameExtension != null &&
fileNameExtension.ToLower().Contains("png"))
{
resizedImg.Save(newFilename, ImageFormat.Png);
}
else
{
success = false;
}
if (success)
{
MessageBox.Show(String.Format("Done! File saved as {0}", newFilename));
}
else
{
MessageBox.Show("Something went awry. The file was not saved");
}
UPDATE 2
So here is my new code, implementing the suggestion, and supporting several new file types:
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Windows.Forms;
namespace FileResizingUtil
{
public partial class FormFileResizer : Form
{
private Image _imgToResize;
String _originalFilename = String.Empty;
public FormFileResizer()
{
InitializeComponent();
}
private void buttonChooseImage_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog
{
InitialDirectory = "c:\\",
Filter = "JPG files (*.jpg)|*.jpg| PNG files (*.png)|*.png| BMP files (*.bmp)|*.bmp| TIFF files (*.tiff)|*.png| ICO files (*.ico)|*.ico| EMF files (*.emf)|*.emf| WMF files (*.wmf)|*.wmf",
FilterIndex = 1, RestoreDirectory = true
};
if (ofd.ShowDialog() == DialogResult.OK)
{
try
{
_originalFilename = ofd.FileName;
_imgToResize = Image.FromFile(_originalFilename);
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
if (String.IsNullOrWhiteSpace(_originalFilename)) return;
// If made it to here, it must be good
String preamble = labelImgSelected.Text;
labelImgSelected.Text = String.Format("{0}{1}", preamble, _originalFilename);
textBoxOrigHeight.Text = _imgToResize.Height.ToString();
textBoxOrigWidth.Text = _imgToResize.Width.ToString();
buttonApplyPercentageChange.Enabled = true;
}
private void buttonResizeImage_Click(object sender, EventArgs e)
{
bool success = true;
// Really large images take awhile, so show an hourglass
Cursor.Current = Cursors.WaitCursor;
try
{
// Two different ways of getting the int val
var size = new Size { Height = Convert.ToInt32(textBoxNewHeight.Text), Width = int.Parse(textBoxNewWidth.Text) };
Image resizedImg = FileResizeUtils.GetResizedImage(_imgToResize, size);
String fileNameSansExtension = Path.GetFileNameWithoutExtension(_originalFilename);
String fileNameExtension = Path.GetExtension(_originalFilename);
String newFilename = String.Format("{0}{1}_{2}{3}", fileNameSansExtension, size.Height, size.Width, fileNameExtension);
if (fileNameExtension != null && fileNameExtension.ToLower().Contains("jpg"))
{
resizedImg.Save(newFilename, ImageFormat.Jpeg);
}
else if (fileNameExtension != null && fileNameExtension.ToLower().Contains("png"))
{
resizedImg.Save(newFilename, ImageFormat.Png);
}
else if (fileNameExtension != null && fileNameExtension.ToLower().Contains("bmp"))
{
resizedImg.Save(newFilename, ImageFormat.Bmp);
}
else if (fileNameExtension != null && fileNameExtension.ToLower().Contains("ico"))
{
resizedImg.Save(newFilename, ImageFormat.Icon);
}
else if (fileNameExtension != null && fileNameExtension.ToLower().Contains("tiff"))
{
resizedImg.Save(newFilename, ImageFormat.Tiff);
}
else if (fileNameExtension != null && fileNameExtension.ToLower().Contains("emf"))
{
resizedImg.Save(newFilename, ImageFormat.Emf);
}
else if (fileNameExtension != null && fileNameExtension.ToLower().Contains("wmf"))
{
resizedImg.Save(newFilename, ImageFormat.Wmf);
}
else
{
success = false;
}
MessageBox.Show(success
? String.Format("Done! File saved as {0}", newFilename)
: "Something went awry. The file was not saved");
Recycle();
}
finally
{
Cursor.Current = Cursors.Default;
}
}
private void Recycle()
{
buttonResizeImage.Enabled = false;
buttonApplyPercentageChange.Enabled = false;
labelImgSelected.Text = "Image selected: ";
textBoxOrigHeight.Text = String.Empty;
textBoxOrigWidth.Text = String.Empty;
// Retain the percentage vals, as it may be that all in a batch need to be the same pair of vals
}
private void buttonApplyPercentageChange_Click(object sender, EventArgs e)
{
int origHeight = _imgToResize.Height;
int origWidth = _imgToResize.Width;
// Two ways to convert the val
double heightFactor = (double)numericUpDownHeight.Value / 100.0;
double widthFactor = Convert.ToDouble(numericUpDownWidth.Value) / 100.0;
if (heightFactor < 0 || widthFactor < 0)
{
// show an error - no negative values allowed- using updown, so that should not be possible
}
var newHeight = Convert.ToInt32(origHeight * heightFactor);
var newWidth = Convert.ToInt32(origWidth * widthFactor);
textBoxNewHeight.Text = newHeight.ToString();
textBoxNewWidth.Text = newWidth.ToString();
buttonResizeImage.Enabled = true;
}
private void textBoxNewHeight_TextChanged(object sender, EventArgs e)
{
EnableResizeButtonIfValidDimensionsEntered();
}
private void EnableResizeButtonIfValidDimensionsEntered()
{
if (String.IsNullOrWhiteSpace(textBoxOrigHeight.Text)) return;
String candidateHeight = textBoxNewHeight.Text;
String candidateWidth = textBoxNewWidth.Text;
int validHeight;
int validWidth;
buttonResizeImage.Enabled = (int.TryParse(candidateHeight, out validHeight)) &&
(int.TryParse(candidateWidth, out validWidth));
}
private void numericUpDownHeight_ValueChanged(object sender, EventArgs e)
{
if (checkBoxRetainRatio.Checked)
{
numericUpDownWidth.Value = numericUpDownHeight.Value;
}
}
private void numericUpDownWidth_ValueChanged(object sender, EventArgs e)
{
if (checkBoxRetainRatio.Checked)
{
numericUpDownHeight.Value = numericUpDownWidth.Value;
}
}
}
}
From the Image.Save documentation:
If no encoder exists for the file format of the image, the Portable
Network Graphics (PNG) encoder is used. When you use the Save method
to save a graphic image as a Windows Metafile Format (WMF) or Enhanced
Metafile Format (EMF) file, the resulting file is saved as a Portable
Network Graphics (PNG) file. This behavior occurs because the GDI+
component of the .NET Framework does not have an encoder that you can
use to save files as .wmf or .emf files.
If you want to save in a different format, use the overloaded Save method, taking format as a second parameter:
Save(String, ImageFormat)
Most image viewers don't use the extension of the file to determine the type of the file, but use so called "magic numbers" (http://en.wikipedia.org/wiki/Magic_number_(programming)#Magic_numbers_in_files). They basically check the first X bytes of the file wich is often unique to a specific image format.
My guess is, that the library you're using saves the file as PNG as default (edit: see Eugenes answer), not considering what extension you put there. IrfanView notices, that the magic number and the extension don't match but still shows the image by defaulting to the magic number.
Go to a console and print out the file. If it is a PNG file, you will see PNG displayed and it stops.
If is is JPEG, you will get a lot of garbage but should see EXIF or JFIF at the top. The very start is FF D8
Because the JPEG and PNG have different signatures, the application can tell them apart from their contents and invite the appropriate decoder.
Image applications normally identify the type of image from the contents of the stream, not the extension.

How can I check if the path entered by user is valid or not? [duplicate]

This question already has answers here:
Check whether a path is valid
(12 answers)
Closed 8 years ago.
I have found this code while I was busy searching for an answer!
private void btnOpenFile_Click(object sender, EventArgs e)
{
OpenFileDialog saveFileDialogBrowse = new OpenFileDialog();
saveFileDialogBrowse.Filter = "Pcap file|*.pcap";
saveFileDialogBrowse.Title = "Save an pcap File";
saveFileDialogBrowse.ShowDialog();
var pcapFile = saveFileDialogBrowse.FileName; //do whatever you like with the selected filename
if (pcapFile != "")
{
FileInfo fileInfo = new FileInfo(pcapFile);
txtFilePath.Text = fileInfo.FullName;
}
}
There is no easy way.
You can use File.Exists to check for file existence on the path, but a change can still happen before the execution of the next line. Your best option is to combine File.Exists with try-catch to catch any possible exceptions.
private void btnOpenFile_Click(object sender, EventArgs e)
{
OpenFileDialog saveFileDialogBrowse = new OpenFileDialog();
saveFileDialogBrowse.Filter = "Pcap file|*.pcap";
saveFileDialogBrowse.Title = "Save an pcap File";
saveFileDialogBrowse.ShowDialog();
var pcapFile = saveFileDialogBrowse.FileName; //do whatever you like with the selected filename
try
{
if (File.Exists(pcapFile))
{
FileInfo fileInfo = new FileInfo(pcapFile);
txtFilePath.Text = fileInfo.FullName;
}
}
catch (FileNotFoundException fileNotFoundException)
{
//Log and handle
}
catch (Exception ex)
{
//log and handle
}
}
You can use the File.Exists method:
string fullPath = #"c:\temp\test.txt";
bool fileExists = File.Exists(fullPath);
You can use the File.Exists method, which is documented here.

How to open a program if the .txt doesn't exist yet?

I've got this code at the start of the form that reads a file that already exists and sets value of 4 textBoxes accordingly to what it's written inside. How do I proceed if the file hasn't yet been created? Any help would be very appreciated.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
FileStream file = new FileStream("cenaEnergentov.txt", FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(file);
sr.ReadLine();
var textLines = File.ReadAllLines("cenaEnergentov.txt");
foreach (var line in textLines)
{
string[] dataArray = line.Split(';');
textBox1.Text = (dataArray[0]);
textBox2.Text = (dataArray[1]);
textBox3.Text = (dataArray[2]);
textBox4.Text = (dataArray[3]);
}
}
If the uper is a false I'd like to proceed with normal script down below that starts with:
public void trackBar1_Scroll(object sender, EventArgs e)
{
......
Use a simple if statement
// I edit this line according to your comment
if(File.Exists(String.Concat("cenaEnergentov".ToUpper(), ".txt"))
{
// do your job
}
else
{
// call appropriate method
trackBar1_Scroll(this,EventArgs.Empty); // for example
}
Try this before you open the file:
var filename = "filename.txt";
if (!File.Exists(filename))
{
File.Create(filename);
}
This won't account for the fact that you're assigning values without checking to see if they exist first. Implementing that is relatively trivial as well.
It also appears that the FileStream and StreamReader are redundant. Just use File.ReadAllLines instead.
The previous solutions will work OK... however they don't really answer the big question:
How do I know when to continue?
The best way would be to use a FileSystemWatcher:
var watcher = new FileSystemWatcher(path, ".txt");
watcher.Created += (sender, e) =>
{
if (e.ChangeType == WatcherChangeTypes.Created)
initForm();
};
Where initForm() is:
void initForm()
{
if(File.Exists(path))
{
// Update form
}
else
{
var watcher = new FileSystemWatcher(path, ".txt");
watcher.Created += (sender, e) =>
{
if (e.ChangeType == WatcherChangeTypes.Created)
initForm();
};
}
}
try this
if(File.Exists("yourFile.txt"))
{
//do what you do
}
else
{
// call appropriate method
}

Categories

Resources