how to pass file path to a variable using openfiledialog control? - c#

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);
}

Related

How can I write those bytes in this case in 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();
}
}

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, ",");
}

Why does media source not work with Safefilenames?

I want to add filenames (without the full path) to the ListBox.
The code below is working smoothly, but when when I change FileNames to SafeFileNames (for hiding item location) it's not working anymore.
XAML
<MediaElement x:Name="mePlayer" Margin="64,0,90,61"/>
<ListBox x:Name="listbox4" Background="Salmon" BorderBrush="Black" BorderThickness="3"/>
CS
private void load_Click(object sender, RoutedEventArgs e)
{
Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();
ofd.DefaultExt = ".mp3";
ofd.Filter = "All|*.*";
ofd.Multiselect = true;
Nullable<bool> result = ofd.ShowDialog();
if (result == true)
{
for (int i = 0; i < ofd.FileNames.Length; i++)
{
listbox4.Items.Add(ofd.FileNames[i].ToString());
listbox4.SelectedItem = ofd.FileName;
mePlayer.Source = new Uri(
listbox4.SelectedItem.ToString(),
UriKind.RelativeOrAbsolute);
mePlayer.LoadedBehavior = MediaState.Play;
}
}
}
This code should work for you. Please read the comments in the code before you proceed.
private Dictionary<string, string> fileDictionary = new Dictionary<string, string>();
private void load_Click(object sender, RoutedEventArgs e)
{
Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();
ofd.DefaultExt = ".mp3";
ofd.Filter = "All|*.*";
ofd.Multiselect = true;
Nullable<bool> result = ofd.ShowDialog();
if (result == true)
{
for (int i = 0; i < ofd.FileNames.Length; i++)
{
var filePath = ofd.FileNames[i];
var fileName = System.IO.Path.GetFileName(filePath);
fileDictionary.Add(fileName, filePath);
// not sure about this logic. You may need to reconsider what you are trying to do here.
//Instead of doing this, create a click event for the list box and get the selected file path to be played from the dictionary.
listbox4.Items.Add(fileName);
}
}
}
private void listbox4_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (listbox4.SelectedItem != null)
{
var selectedFile = listbox4.SelectedItem.ToString();
string selectedFilePath;
fileDictionary.TryGetValue(selectedFile, out selectedFilePath);
if (!string.IsNullOrEmpty(selectedFilePath))
{
mePlayer.Source = new Uri(selectedFilePath, UriKind.RelativeOrAbsolute);
mePlayer.LoadedBehavior = MediaState.Play;
}
}
}

How to pass file dialog Instance as a parameter in C#

I am trying to compare two images by using picture box, but I got a problem: How can I pass the selected picture name as a parameter to a function as a string?
I save picture path and name as a string name1 and string name2, but I got a problem when I pass them as parameters.
Below is my code. Please tell me where I am wrong.
private void pictureBox1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd1 = new OpenFileDialog();
ofd1.Title = "Select User Profile Image";
ofd1.Filter = "Image File(*.png;*.jpg;*.bmp;*.gif)|*.png;*.jpg;*.bmp;*.gif";
if (ofd1.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image = new Bitmap(ofd1.FileName);
string name1 = ofd1.FileName;
}
}
private void button1_Click(object sender, EventArgs e)
{
Compare(name1,name2);
}
public void Compare(string bmp1, string bmp2, byte threshold = 3)
{
Bitmap firstBmp = (Bitmap)Image.FromFile(bmp1);
Bitmap secondBmp = (Bitmap)Image.FromFile(bmp2);
firstBmp.GetDifferenceImage(secondBmp, true);
string result = string.Format("Difference: {0:0.0} %", firstBmp.PercentageDifference(secondBmp, threshold) * 100);
}
You create variable name1 inside if statement inside pictureBox1_Click(). You should create class level variable to use it inside button1_Click(), because name1 is visible only inside if block:
public YourClass
{
string name1 = String.Empty:
//..... your code
private void pictureBox1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd1 = new OpenFileDialog();
ofd1.Title = "Select User Profile Image";
ofd1.Filter = "Image File(*.png;*.jpg;*.bmp;*.gif)|*.png;*.jpg;*.bmp;*.gif";
if (ofd1.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image = new Bitmap(ofd1.FileName);
name1 = ofd1.FileName;
}
}
private void button1_Click(object sender, EventArgs e)
{
Compare(name1,name2);
}
public void Compare(string bmp1, string bmp2, byte threshold = 3)
{
Bitmap firstBmp = (Bitmap)Image.FromFile(bmp1);
Bitmap secondBmp = (Bitmap)Image.FromFile(bmp2);
firstBmp.GetDifferenceImage(secondBmp, true);
string result = string.Format("Difference: {0:0.0} %", firstBmp.PercentageDifference(secondBmp, threshold) * 100);
}
}
If you create name2 the same way, you should make it class level variable too.
You can declare a member variable in your Form to save the file path:
public partial class YourForm : Form
{
private string _imagePath1;
private string _imagePath2;
private void pictureBox1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd1 = new OpenFileDialog();
// ... your code
if (ofd1.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image = new Bitmap(ofd1.FileName);
// SAVE PATH TO CLASS MEMBER
_imagePath1 = ofd1.FileName;
}
}
private void button1_Click(object sender, EventArgs e)
{
// USE CLASS MEMBERS
Compare(_imagePath1, _imagePath2);
}
}
I think below URL is helpful to you
http://www.c-sharpcorner.com/uploadfile/prathore/image-comparison-using-C-Sharp

c# Get File Name

private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog newOpen = new OpenFileDialog();
DialogResult result = newOpen.ShowDialog();
this.textBox1.Text = result + "";
}
It just returns "OK"
What am I doing wrong? I wish to get the PATH to the file and display it in a text box.
The ShowDialog method returns whether the user pressed OK or Cancel. This is useful information, but the actual filename is stored as a property on the dialog
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog newOpen = new OpenFileDialog();
DialogResult result = newOpen.ShowDialog();
if(result == DialogResult.OK) {
this.textBox1.Text = newOpen.FileName;
}
}
You need to access the filename:
string filename = newOpen.FileName;
or filenames, if you allowed multiple file selection:
newOpen.FileNames;
Ref.: OpenFileDialog Class
private void button1_Click(object sender, System.EventArgs e) {
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\" ;
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
openFileDialog1.FilterIndex = 2 ;
openFileDialog1.RestoreDirectory = true ;
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
// Insert code to read the stream here.
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file. Error: " + ex.Message);
}
}
}
You need to read the FileName property of the OpenFileDialog instance. This will get you the path of the selected file.
Here is an example of using an existing file as a default, and getting a new file back:
private string open(string oldFile)
{
OpenFileDialog newOpen = new OpenFileDialog();
if (!string.IsNullOrEmpty(oldFile))
{
newOpen.InitialDirectory = Path.GetDirectoryName(oldFile);
newOpen.FileName = Path.GetFileName(oldFile);
}
newOpen.Filter = "eXtensible Markup Language File (*.xml) |*.xml"; //Optional filter
DialogResult result = newOpen.ShowDialog();
if(result == DialogResult.OK) {
return newOpen.FileName;
}
return string.Empty;
}
Path.GetDirectoryName(file) : Return path
Path.GetFileName(file) : Return filename

Categories

Resources