OpenFileDialog opening twice in my C# program - c#

I am having a problem with a with a code that I used for my C# application. When I click on the browse button and select the file dialogue box opens twice.
private void txt_location_TextChanged(object sender, EventArgs e)
{
string folderPath = "";
FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK) {
folderPath = folderBrowserDialog1.SelectedPath;
}
}
private void Button21_Click(object sender, EventArgs e)
{
using(var fbd = new FolderBrowserDialog()) {
DialogResult result = fbd.ShowDialog();
if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath)) {
selectedPath = fbd.SelectedPath;
txt_location.Text = selectedPath;
}
}
}
private void bunifuThinButton21_Click_1(object sender, EventArgs e)
{
System.IO.StreamWriter file;
bool isvalid = ValidateInputs();
try {
file = new System.IO.StreamWriter(selectedPath + # "\dred.txt");
catch (Exception ex) {
MessageBox.Show("Please, Select valid Path..");
return;
}
try {
if (isvalid) {
WriteLines(file);
}
}
catch (Exception ex2) {
MessageBox.Show(ex2.Message);
}
finally {
file.Close();
}
}
}
Obviously, it is only meant to open once to enable me to read the selected file. This works, but only once I have selected the file twice.
Thanks in advance for your help.

You have FolderBrowserDialog being instantiated and shown on two different events:
txt_location_TextChanged
and
Button21_Click
You're having two popups because each one is firing once separately.
You should probably remove the event txt_location_TextChanged entirely unless you need it for another thing that isn't popping the FolderBrowserDialog again.

Related

How to make the user slect a specific file? (C#)

i wanna make a button that opens a check file dialog and after that check if that file is the correct one,thanks. file name is key.txt,i already tried to get it but i have a way to check the path,i need help.
private void button5_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.ShowDialog();
if (System.IO.File.Exists("E:\\Key\\key.txt"))
{
MessageBox.Show("Injected");
}
else
{
MessageBox.Show("Wrong File");
}
}
This is what i have,any solution?
It sounds like you just want to filter the available files that someone can select to those which match a particular file name, but still allow users to find that file in any folder.
Use the Filter property on the OpenFileDialog.
var ofd = new OpenFileDialog();
ofd.Filter = "key files|key.txt";
var dialogResult = ofd.ShowDialog();
if (dialogResult == DialogResult.OK && ofd.CheckFileExists)
{
MessageBox.Show("Injected " + ofd.FileName);
}
else
{
MessageBox.Show("Cancelled");
}
private void button5_Click(object sender, EventArgs e)
{
var ofd = new OpenFileDialog
{
Filter = "Key files (key.txt)|key.txt",
};
if (ofd.ShowDialog() == DialogResult.OK && File.Exists(ofd.FileName))
{
MessageBox.Show("Injected");
}
else
{
MessageBox.Show("Wrong File");
}
}
but I strongly recommend you to add OpenFileDialog as a form control, so the code look like:
private void button5_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK && File.Exists(openFileDialog1.FileName))
{
MessageBox.Show("Injected");
}
else
{
MessageBox.Show("Wrong File");
}
}
Configure filter in property window:

Windows form not responding: How can I resolve this issue?

I create a windows service and a setup project.
During the installation of the windows service, I add a windows form which allow the user to upload a file in the project folder but when I click on the button to upload the file my windows form is always on state not responding
ProjectInstaller of my windows service
public override void Install(IDictionary stateSaver)
{
base.Install(stateSaver);
Form1 validationForm = new Form1();
validationForm.ShowDialog();
}
Windows form
public Form1()
{
InitializeComponent();
}
private void button1_Click_1(object sender, EventArgs e)
{
try
{
OpenFileDialog fileDialog = new OpenFileDialog();
//fileDialog.Filter = "Dat files |*.dat";
fileDialog.Multiselect = false;
if (fileDialog.ShowDialog() == DialogResult.OK)
{
var path = fileDialog.FileName;
Process.Start(path);
}
}
catch (Exception)
{
MessageBox.Show("An error occured", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
I think Process.Start(path); block UI thread.
Try to use Task.Run(() => Process.Start(a)); instead.
Your UI is locked up due to a long running process which is why you see "Not responding"
Mark your Click Async:
private async void button1_Click_1(object sender, EventArgs e)
and
await Task.Run(() =>
{
//Insert the long running stuff here
Process.Start(path);
});
Try this.
private void button1_Click(object sender, EventArgs e)
{
var task = new Thread(() => GetFile());
task.SetApartmentState(ApartmentState.STA);
task.Start();
task.Join();
}
private static void GetFile()
{
try
{
OpenFileDialog fileDialog = new OpenFileDialog();
//fileDialog.Filter = "Dat files |*.dat";
fileDialog.Multiselect = false;
if (fileDialog.ShowDialog() == DialogResult.OK)
{
var path = fileDialog.FileName;
Process.Start(path);
}
}
catch (Exception)
{
MessageBox.Show("An error occured", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

Overwrite file only works once

I have a simple program that copies files and directories from one place to another. I have it set-up that if there are any exceptions (such as if access to the path is denied) it will create a log file with the error.
I have a button that when pressed, performs the copy action. Everything works fine the first time I press the button and the log file is either created or overwritten with the appropriate error messages.
However, if I press the button a second time, the text file is not overwritten and instead the error messages append. If I close out of my program and run it again, the file is overwritten on the first button press. Any thoughts would be greatly appreciated.
target is a string filepath which I'm getting from a FolderBrowserDialog and taking the selected path and setting it to a textbox. loglist is just a simple List<string> I'm using to store the error messages from any exceptions that occur during the copy process.
public partial class Form1 : Form
{
static List<string> logList = new List<string>();
public Form1()
{
InitializeComponent();
}
private static void CopyAll(DirectoryInfo source, DirectoryInfo target)
{
if (source.FullName.ToLower() == target.FullName.ToLower())
return;
if (Directory.Exists(target.FullName) == false)
{
Directory.CreateDirectory(target.FullName);
}
foreach (FileInfo fi in source.GetFiles())
{
try
{
fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);
}
catch (Exception ex)
{
logList.Add(ex.Message);
}
}
foreach (DirectoryInfo diSourceSub in source.GetDirectories())
{
DirectoryInfo nextTargetSubDir = target.CreateSubdirectory(diSourceSub.Name);
CopyAll(diSourceSub, nextTargetSubDir);
}
}
private void directoryPickerBtn1_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderDialog = new FolderBrowserDialog();
DialogResult folderResult = folderDialog.ShowDialog();
if (folderResult == DialogResult.OK)
{
directoryTextbox1.Text = folderDialog.SelectedPath;
}
}
private void directoryPickerBtn2_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderDialog = new FolderBrowserDialog();
DialogResult folderResult = folderDialog.ShowDialog();
if (folderResult == DialogResult.OK)
{
directoryTextbox2.Text = folderDialog.SelectedPath;
}
}
private void copyBtn_Click(object sender, EventArgs e)
{
string source = (directoryTextbox1.Text);
string target = (directoryTextbox2.Text);
DirectoryInfo dirSource = new DirectoryInfo(source);
DirectoryInfo dirTarget = new DirectoryInfo(target);
try
{
CopyAll(dirSource, dirTarget);
if (logList.Count > 0)
{
using (StreamWriter sw = new StreamWriter(target + #"\log.txt", false))
{
foreach (string error in logList)
{
sw.WriteLine(error);
}
}
}
DialogResult result = MessageBox.Show("Copy Succeeded", "Success");
if (result == DialogResult.OK)
{
string myPath = dirTarget.ToString();
System.Diagnostics.Process prc = new System.Diagnostics.Process();
prc.StartInfo.FileName = myPath;
prc.Start();
}
}
catch (Exception)
{
MessageBox.Show("Copy Failed", "Failed");
}
}
}
}
As #Reza Aghaei pointed out in comments, the problem is that you do not clear the logList.
The file gets created anew every time, but each time you click the Copy button, the loglist still contains the results of the previous copy action.
So you need to clear the list when starting a new copy:
private static void CopyAll(DirectoryInfo source, DirectoryInfo target)
{
logList.Clear();
// ...
From your code it seems that you never clear the logList, this means that it appears the file is being appending because the logList still contains all of the old entries.
You'll need to clear the list between copies if you only want relevant entries to that copy, either before you start copying or after you finish writing the file.
This would be better as a separate method
try
{
CopyAll(dirSource, dirTarget);
SaveLog(target + #"\log.txt");
ClearLog();
//...
}
private void SaveLog(string filename)
{
if (logList.Count > 0)
{
FileStream fs = File.Open(target + #"\log.txt", FileMode.Create);
using (StreamWriter sw = new StreamWriter(fs))
{
foreach (string error in logList)
{
sw.WriteLine(error);
}
}
}
}

c# Filedialog problems

I have a question about the opfiledialog function within c#. When i dont select a file with openfiledialog it put's a text automaticly in my textbox. That text will be "filedialog1". What can i do to fix this.
using System;
using System.Windows.Forms;
using System.IO;
namespace Flashloader
{
public partial class NewApplication : Form
{
private toepassinginifile _toepassinginifile;
private controllerinifile _controllerinifile;
//private controllerinifile _controlIniFile;
public NewApplication(toepassinginifile iniFile)
{
_controllerinifile = new controllerinifile();
_toepassinginifile = iniFile;
InitializeComponent();
controllerComboBox.DataSource = _controllerinifile.Controllers;
}
public bool Run()
{
var result = ShowDialog();
return result == System.Windows.Forms.DialogResult.OK;
}
private void button4_Click(object sender, EventArgs e)
{
this.Close();
}
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "Srec Files (.a20; .a21; .a26; .a44)|*.a20; *.a21; *.a26; *.a44|All files (*.*)|*.*";
openFileDialog1.Title = ("Choose a file");
openFileDialog1.InitialDirectory = Path.Combine(Directory.GetCurrentDirectory());
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
fileBox.Text = (System.IO.Path.GetFileName(openFileDialog1.FileName));
}
}
private void button3_Click(object sender, EventArgs e)
{
Toepassing toepassing = new Toepassing();
toepassing.Name = nameBox.Text;
toepassing.Controller = (Flashloader.Controller)controllerComboBox.SelectedItem;
toepassing.TabTip = descBox.Text;
toepassing.Lastfile = openFileDialog1.FileName;
fileBox.Text = openFileDialog1.FileName;
if (nameBox.Text == "")
MessageBox.Show("You haven't assigned a Name");
else if (controllerComboBox.Text == "")
MessageBox.Show("You haven't assigned a Controller");
else if (descBox.Text == "")
MessageBox.Show("You haven't assigned a Desciption");
else if (fileBox.Text == "")
MessageBox.Show("You haven't assigned a Applicationfile");
_toepassinginifile.ToePassingen.Add(toepassing);
_toepassinginifile.Save(toepassing);
MessageBox.Show("Save Succesfull");
DialogResult = DialogResult.OK;
this.Close();
}
private void button2_Click(object sender, EventArgs e)
{
var newcontroller = new Newcontroller(_controllerinifile);
newcontroller.ShowDialog();
controllerComboBox.DataSource = null;
controllerComboBox.DataSource = _controllerinifile.Controllers;
}
}
}
Thanks all for the help
private void button3_Click(object sender, EventArgs e)
{
toepassing.Lastfile = openFileDialog1.FileName;// Dont do this
fileBox.Text = openFileDialog1.FileName; //or this
Its unclear to me why you are holding onto an Open file dialog I would personally do the following
using(OpenFileDialog ofd = new OpenFileDialog())
{
if(ofd.ShowDialog() == DialogResult.OK)
{
classStringVariable = ofd.FileName;
fileBox.Text = ofd.FileName;
}
}
Then in button 3
toepassing.LastFile = classStringVariable ;
fileBox.Text = classStringVariable ;
When you use the Form Designer to add an OpenFileDialog control on you form, the designer assigns at the property FileName the value openFileDialog1.
I suppose you have set something as the initial value for the property FileName. Then in button_click3 you have no mean to check for the DialogResult and thus you get inconditionally this default back.
Fix it removing this default from the designer FileName property
Just add openFileDialog1.FileName= ""; before you show the dialog.
openFileDialog1.Filter = "Srec Files (.a20; .a21; .a26; .a44)|*.a20; *.a21; *.a26; *.a44|All files (*.*)|*.*";
openFileDialog1.Title = ("Choose a file");
openFileDialog1.InitialDirectory = Path.Combine(Directory.GetCurrentDirectory());
openFileDialog1.RestoreDirectory = true;
openFileDialog1.FileName = "";
if (openFileDialog1.ShowDialog() == DialogResult.OK && openFileDialog1.FileName != "")
{
fileBox.Text = (System.IO.Path.GetFileName(openFileDialog1.FileName));
}
In your button3_Click event you're checking for an empty string file name anyways, so they would get the correct error message and they wouldn't have some weird arbitrary default name show up when they open the dialog.

How do I upload to dropbox using dropnet?

I am using DropNet. I have problem with upload file into DropBox.
I am sure the connection with dropbox in fine. when I changed the method of upload to create file and delete file method that works fine.
I really can not see any problem that why is not uploading? I use exactly same API as DropNet.
protected void Btn_upload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
if (Session["DropNetUserLogin"] != null)
{
try
{
_client.UseSandbox = true;
_client.UploadFile("/", FileUpload1.FileName, FileUpload1.FileBytes);
}
catch (Exception ex)
{
litOutput.Text = "Error in upload user login in session " + ex.Message;
}
}
else
{
litOutput.Text = "Session expired...";
}
}
else
{
litOutput.Text = "You did not specify a file to upload.";
}
}
}
Here is code which worked for me, hoping that this may help you:
private void button1_Click(object sender, RoutedEventArgs e)
{
var dlg = new OpenFileDialog();
dlg.Filter = "Text documents (.txt)|*.txt";
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
string filename = dlg.FileName;
FileNameTextBox.Text = filename;
}
var x = #"/" + Path.GetFileName(FileNameTextBox.Text);
_client.UploadFile("/", Path.GetFileName(FileNameTextBox.Text), File.ReadAllBytes(#"" + FileNameTextBox.Text));
}

Categories