YesNo Dialog Appears Even if There is No Duplicated File - c#

I'm trying to make sure that the user doesn't download a file that will replace an existing downloaded (same) file. Hence, I tried to create YesNo dialog for the user to confirm. However, even if there's no "sample.xml" in that folder, the YesNo dialog will still appear when the user click on Download button. May I know where did I do wrongly? I am lacking programming knowledge, sorry and please bear with me.
My code as below:
private void btnDownloadXML2_Click(object sender, EventArgs e)
{
if (#"..\..\sharePriceXML\" + txtSharePriceSymbol.Text.ToString() + ".xml" != null)
{
DialogResult dialogResult = MessageBox.Show("Are you sure you want to re-download the file? This will replace the old file!", "Warning", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
using (WebClient client = new WebClient())
{
client.DownloadFile("http://www.lse.co.uk/chat/" + txtSharePriceSymbol.Text.ToString(),
#"..\..\sharePriceXML\" + txtSharePriceSymbol.Text.ToString() + ".xml");
}
MessageBox.Show("Download Completed! File has been placed in the folder sharePriceXML!");
}
else if (dialogResult == DialogResult.No)
{
MessageBox.Show("The file is not downloaded. Your old file remains.");
}
}
else if (#"..\..\sharePriceXML\" + txtSharePriceSymbol.Text.ToString() + ".xml" == null)
{
using (WebClient client = new WebClient())
{
client.DownloadFile("http://www.lse.co.uk/chat/" + txtSharePriceSymbol.Text.ToString(),
#"..\..\sharePriceXML\" + txtSharePriceSymbol.Text.ToString() + ".xml");
}
MessageBox.Show("Download Completed! File has been placed in the folder sharePriceXML!");
}
}

You're checking the file path as a string to see if it's null.. it's never null, because it has the file path.
You'll need to use File.Exists(). Instead of this:
if (#"..\..\sharePriceXML\" + txtSharePriceSymbol.Text.ToString() + ".xml" != null)
Use this:
if (File.Exists(#"..\..\sharePriceXML\" + txtSharePriceSymbol.Text.ToString() + ".xml"))

Related

C# Path.GetFileName() as well as OpenFileDialog.SafeFileName cuts off the underscores in the filename

In my company it is common to name files in the following manner: 210808_Filename.extension
Unfortunately both of these ways to get the filename failed: Path.GetFileName() and OpenFileDialog.SafeFileName. In the path itself the underscores exist, but in the filename they get removed.
private void btnOpenFile_Click(object sender, RoutedEventArgs e)
{
string strCheck = "";
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.ShowDialog();
strConfigPath1 = openFileDialog1.FileName;
if (strConfigPath1.Length > 6)
{
strCheck = strConfigPath1.Substring(strConfigPath1.Length - 6);
}
if (strConfigPath1 == "" || strCheck != ".gcode")
{
MessageBox.Show("Selected file has to be a GCode file.");
}
else
{
lblSelectedDocument.Content = System.IO.Path.GetFileName(string);
}
}
I know it may not be a well programmed code due to the fact I am bloody new to programming. Sorry for that.
Here's a straightforward way to set the contents of the label, based on the file that the user selects:
private void btnOpenFile_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
if (openFileDialog.ShowDialog() == true)
{
string chosenFilename = openFileDialog.FileName;
if (Path.GetExtension(chosenFilename).ToLower() == ".gcode")
{
lblSelectedDocument.Content = "Valid file. You selected " + chosenFilename;
}
else
{
lblSelectedDocument.Content = "Invalid file - not a .GCODE file. You selected " + chosenFilename;
}
}
else
{
lblSelectedDocument.Content = "You did not select a file.";
}
}
If the user doesn't select a file, we just set the label to be You did not select a file.
If the user did select a file, we check if the file extension is our intended extension. The check is case-insensitive, so .GCODE, .GcOdE, .gcode (etc) will all work. If the user selected a gcode file, the label says the filename is valid and shows the filename.
If the file extension doesn't match, the user must have selected an invalid file. When this occurs we tell them the filename is invalid and show the filename.

save the content of the text box to a variable c#

I have the following method in windows form
private void btnSelectNuevo_Click(object sender, EventArgs e)
{
if (openFileDialog2.ShowDialog() == DialogResult.OK)
{
try
{
string fichero = openFileDialog2.FileName.ToString();
txtbox_sel_fich.Text = fichero;
if (string.IsNullOrEmpty(txtbox_sel_fich.Text) == true)
{
MessageBox.Show("file not selected", "return file selection", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
catch (SecurityException ex)
{
MessageBox.Show($"Security error.\n\nError message: {ex.Message}\n\n" +
$"Details:\n\n{ex.StackTrace}");
}
}
}
and another method:
private void btnsubir_Click(object sender, EventArgs e)
{
string reply = "";
string fichero = "";
fichero = textbox_select.Text.ToString();
// string ruta = textbox_select.Text.ToString();
// FileInfo fich = new FileInfo(ruta);
// fichero = fich.Name;
if (fichero == readLastFile(fichero))
{
createLog(fichero + ":this file" + fichero + " You have already been imported previously. No action is realized\n");
MessageBox.Show("This file" + "'" + fichero + "'" + " You have already been imported");
}
else
{..
how can you see I have a method called "readLastFile (fichero)"; what it does is check in MySql in the "File" table if there is a file already imported with that name that I pass as a parameter, if it exists it does not import it to the DDBB and the program ends but if it does not exist it does the import.
The problem I have is that the file variable stores the entire path of an excel file (c: \ ... \ helloWord.xlsx) when what I want is that it only stores (helloWord.xlsx) since when I am going to do the check tells me it doesn't exist and starts loading when it shouldn't.
Some help?
I don't know if I am saving it correctly. THANKS FOR YOUR SUPPORT
I have is that the file variable stores the entire path of an excel file (c: \ ... \ helloWord.xlsx) when what I want is that it only stores (helloWord.xlsx)
Use Path.GetFileName(...)
Path is part of the System.IO namespace

I have a problem in saving file with the FolderBrowserDialog

I have this code:
private void button1_Click(object sender, EventArgs e)
{
string x = "Name: " + label1.Text + " " + "FamilyName: " + label2.Text + " " + "FatherName: " + label3.Text + " " + "PhoneNumber: " + label4.Text;
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
if (radioButton1.Checked == true)
{
System.IO.File.WriteAllText(folderBrowserDialog1.SelectedPath + label1.Text + ".txt", x);
MessageBox.Show("The file registered.");
}
else if (radioButton2.Checked == true)
{
System.IO.File.WriteAllText(folderBrowserDialog1.SelectedPath + label1.Text + ".doc", x);
MessageBox.Show("The file registered.");
}
else
{
MessageBox.Show("Please choose one of the formats.");
}
}
}
And this is for store some information from labels in a file, and dynamically selects the file name from label1. Then I put a radio button to choose between saving the file in txt format or doc format. After selecting one of the formats and clicking on the Save button, the folderBrowserDialog opens so I can choose the path I want to save my file there. But when I chose my path, let's say that I chose this path: 'G:\SavingFile\TextFiles', instead of saving the file in the TextFiles folder, saves it in the SavingFile folder.
My question is why it doesn't save the file in the last folder? And how can I fix it?
You should not concatenate your paths as string but use System.IO.Path.Combine instead. as this will also take care of the correct path-separators, which are missing from your code as SelectedPath does not end with a path-separator
So in your case
var filepath = System.IO.Path.Combine(folderBrowserDialog1.SelectedPath, label1.Text + ".txt");
System.IO.File.WriteAllText(filepath, ....);
This will take care of the required path separators.
If you are using .Net Core you might also use System.IO.Path.Join. But be aware there are some differences in the behaviour of these two methods with regards to rooting the resulting path. See the linked docs for details.
I also found another way to save my files that is easier than the way that I did above. I can simply use saveFileDialog.
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
System.IO.File.WriteAllText(saveFileDialog1.FileName, x);
}

How do I store the Directory name chosen from FolderBrowserDialog() in wpf?

I have a "settings" button in one of my programs that will be used to grab a directory that the user wants to work with.
After they select a directory, I'd like to be able to return three pieces of information.
The name of the directory chosen.
The number of files in that directory (just files, not other directories)
A list with the names of every file in the directory.
I have been looking through this page, and I found the GetFiles() method, but I haven't figured out how to get the name of the directory. Any nudge in the right direction is appreciated.
Here's what I have so far.
public void SettingsButton(object sender, RoutedEventArgs e)
{
var dialog = new System.Windows.Forms.FolderBrowserDialog();
System.Windows.Forms.DialogResult result = dialog.ShowDialog();
if (result == System.Windows.Forms.DialogResult.OK)
{
string[] files = Directory.GetFiles(dialog.SelectedPath);
MessageBox.Show("files found" + files.Length.ToString(), "Message");
}
}
I know the code above doesn't return the names of the files, but I know the rough idea on how to do that, I just haven't implemented it yet....so my questions just about storing the directory they chose as a string.
here's an example how you can do this, a simple foreach:
public void SettingsButton(object sender, RoutedEventArgs e)
{
var dialog = new System.Windows.Forms.FolderBrowserDialog();
System.Windows.Forms.DialogResult result = dialog.ShowDialog();
if (result == System.Windows.Forms.DialogResult.OK)
{
string[] files = Directory.GetFiles(dialog.SelectedPath);
string resultStr = string.Empty;
foreach (String item in files)
{
resultStr += item.ToString() + "\n";
}
MessageBox.Show("path:" + dialog.SelectedPath + "\n" +
"files: " + files.Count().ToString() + "\n" +
resultStr, "Message");
}
}
using System.Windows.Forms;
FolderBrowserDialog() dialog = new FolderBrowserDialog();
DialogResult result = dialog.ShowDialog();
Here result will have the selected folder.

How to give userchoice file name in browserdialog box

Hi in my windows form application i want to save some data in a folder and when user selcts the browse button it should browse to reqired folder and should consist of a textbox to enter the filename of user choice. How can i achieve this . The below code is not working for me
private void OutputFolder_button_Click(object sender, EventArgs e)
{
FolderBrowserDialog fd = new FolderBrowserDialog();
try
{
if (fd.ShowDialog() == DialogResult.OK)
{
if (string.IsNullOrEmpty(OutputFolder.Text))
{
MessageBox.Show(" Please provide output file to do backup ");
return;
}
outputFileName = fd.SelectedPath + "\\" + outputFileName;
File.Create(outputFileName).Dispose();
OutputFolder.Text = outputFileName;
//File.Create(outputFileName);
DisplayMainWindow("Selected path to backup" + outputFileName);
Logger.Log("Selected path to backup" + outputFileName);
}
}
catch (Exception ex)
{
MessageBox.Show("Exception" + ex);
}
Sounds like you need the SaveFileDialog class.
You need a SaveFileDialog.
The example in the MSDN page should be enough to get you started.

Categories