C# Windows fourms VS2012 - If statement not executing - c#

I'm trying to make a simple program to either copy, move or sync (update and replace) files. I have a combobox where you select Copy, Move or Sync and so far I've only written a statement for when "Copy" is selected, and it calls a function that contains the process and sends in 2 args which is the source and destination for the files.
During debug it wasn't doing anything when I clicked the start button, so I ran through the code step by step selected "Copy" from the combobox entered the source and destination and pressed start and as it was highlighting each line, the IF statement for copy got highlighted but then carried on to the next ELSE IF and completely ignored the instructions under the "Copy" IF statement. Could you help me debug this problem please? I've checked for spelling errors and typos but I can't seem to find any, I don't understand why it's not executing it.
Thanks, my code is below.
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;
namespace File_Operator
{
public partial class FileOperatorV1 : Form
{
public FileOperatorV1()
{
InitializeComponent();
}
//Browse for source directory
private void sBrowse_Click(object sender, EventArgs e)
{
// Create a new instance of FolderBrowserDialog.
FolderBrowserDialog folderBrowserDlg = new FolderBrowserDialog();
// A new folder button will display in FolderBrowserDialog.
folderBrowserDlg.ShowNewFolderButton = true;
//Show FolderBrowserDialog
DialogResult dlgResult = folderBrowserDlg.ShowDialog();
if (dlgResult.Equals(DialogResult.OK))
{
//Show selected folder path in textbox1.
textBox1.Text = folderBrowserDlg.SelectedPath;
//Browsing start from root folder.
Environment.SpecialFolder rootFolder = folderBrowserDlg.RootFolder;
}
}
//Browse for destination directory
private void dBrowse_Click(object sender, EventArgs e)
{
// Create a new instance of FolderBrowserDialog.
FolderBrowserDialog folderBrowserDlg = new FolderBrowserDialog();
// A new folder button will display in FolderBrowserDialog.
folderBrowserDlg.ShowNewFolderButton = true;
//Show FolderBrowserDialog
DialogResult dlgResult = folderBrowserDlg.ShowDialog();
if (dlgResult.Equals(DialogResult.OK))
{
//Show selected folder path in textbox2.
textBox2.Text = folderBrowserDlg.SelectedPath;
//Browsing start from root folder.
Environment.SpecialFolder rootFolder = folderBrowserDlg.RootFolder;
}
}
//Start button
private void button1_Click(object sender, EventArgs e)
{
//If comboBox1 is equal to "Copy" do this
if (comboBox1.SelectedText == "Copy")
{
//Set var "s" to the contents of textBox1
string s = textBox1.Text;
//Set var "d" to the contents of textBox2
string d = textBox2.Text;
//Run function copyDirectory with var "d" and "s" as the args
copyDirectory(s,d);
}
//If comboBox1 is equal to "Move" do this
else if (comboBox1.SelectedText == "Move")
{
}
//If comboBox1 is equal to "Sync" do this
else if (comboBox1.SelectedText == "Sync")
{
}
}
//copyDirectory function
public static void copyDirectory(string Src, string Dst)
{
String[] Files;
if (Dst[Dst.Length - 1] != Path.DirectorySeparatorChar)
Dst += Path.DirectorySeparatorChar;
if (!Directory.Exists(Dst)) Directory.CreateDirectory(Dst);
Files = Directory.GetFileSystemEntries(Src);
foreach (string Element in Files)
{
// Sub directories
if (Directory.Exists(Element))
copyDirectory(Element, Dst + Path.GetFileName(Element));
// Files in directory
else
File.Copy(Element, Dst + Path.GetFileName(Element), true);
}
}
}
}
It reads this line
if (comboBox1.SelectedText == "Copy")
Ignores this
//Set var "s" to the contents of textBox1
string s = textBox1.Text;
//Set var "d" to the contents of textBox2
string d = textBox2.Text;
//Run function copyDirectory with var "d" and "s" as the args
copyDirectory(s,d);
And then carries on to here
else if (comboBox1.SelectedText == "Move")
I really don't understand why it's being ignored, and I'm very sure I've been selecting "Copy" in the combobox before any asks. Any help is appreciated. Many thanks.

I think instead of using SelectedText you should use Text. It gets or sets the text associated with this control.
if (comboBox1.Text == "Copy")
Here, problem with comboxBox1.SelectedText is that it gets the text that is selected in the editable portion of a ComboBox.
Check MSDN Reference.

Related

c# openFileDialog1.InitialDirectory from string

Am pretty new to C# and i need some help on a project i make.
I making an application we need. The application is to search our DB2 for the case number given on textbox by user. This is working fine i retrieve all data i need just fine. Now i want to click a button and open file dialog and user can select one of the files that exists in a folder on our win server under the folder that exists and named with the case number given in text box. So the initial directory should be dynamically changed according to the value in the textbox.
On my first attempt i declared the case number on a
string public String Gazm = "155465";
then i called initial directory
openFileDialog1.InitialDirectory = $#"\\apollo\zm\{Gazm}";
and worked fine. Dialogue opened on \\apollo\zm\155465\ and i could choose the files in the folder. I was was happy and i thought that that was easy and that i now have only to change the value of Gazm variable to the one given by user and i will do that easy with:
Gazm = textBox2.Text;
.So i did all happy and when i clicked the button the dialogue opened in the \\apollo\zm\ and not at the \\apollo\zm\Gazm\ where Gazm = textbox.text.
I thought there is something wrong with the string construction so what i tried next is that i made a String foldername = $#"\\apollo\zm\"; and public string fld = ""; . then i edit in button_click where the case number from user is captured the string fld = foldername + azm; and i send this result to be displayed in a textbox to check if the result is the desired.
The result in the textbox was the desired path to the case's number folder but the openfiledialogue will still open on the \\apollo\zm\ where then path in the textbox was the \\apollo\zm\155465\ where 155465 was the case number i typed in the textbox.
As i told you am new in C# and i dont know if what am doing is possible.
Please be kind with noob ;)
i will paste my code now which is only the code that reffers to the openfile dialogue. I made a new solution just for that part so i can do my tests on test solution rather than my main project.
Thank you for any help .
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 static System.Windows.Forms.VisualStyles.VisualStyleElement.Tab;
namespace AutoZhm
{
public partial class Form1 : Form
{
String Gazm = "";
String filename = "";
String foldername = $#"\\apollo\zm\";
public string fld = "";
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
String Gazm = textBox1.Text;
string fld = foldername + azm;
textBox97.Text = fld;
}
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
}
private void button4_Click_1(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = fld;
openFileDialog1.Title = "Browse Text Files";
openFileDialog1.CheckFileExists = true;
openFileDialog1.CheckPathExists = true;
openFileDialog1.DefaultExt = "txt";
openFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
openFileDialog1.ReadOnlyChecked = true;
openFileDialog1.ShowReadOnly = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
textBox97.Text = openFileDialog1.FileName;
filename = textBox97.Text;
}
}
}
}
You have the fld variables defined twice, once in your class and once within your button1_Click method. I suspect that this is causing you trouble.
The fld variable within the button1_Click is defined as a local variable. Meaning that it only exists within that method. The fld variable defined in your class is not updated by this method as a result, in fact in the code you've shown it well never change from an empty string.
You can easily fix this by removing the type declaration (string fld = [..] to fld = [..]) within the button1_Click method. That will cause the code to use the class defined variable (which the button4_Click_1 can also access).
Now, as you want an adjustment of the input in your TextBox to determine the initial directory, you'll need to set openFileDialog1.InitialDirectory to the current value textBox97.Text.

Using textbox to gather user's destination path for exporting a CSV in C# Windows application?

I'm looking for an option that allows a user to input their destination folder (Usually copy/Paste) into a text box on a Windows Application, and append the file's name with a specific name. However, I'm stuck as to how to accomplish this.
//Exporting to CSV.
string folderPath = MessageBox.Show(textBox1_TextChanged);
File.WriteAllText(folderPath + "DIR_" + (DateTime.Now.ToShortDateString()) + ".csv", csv);
So it can look like: C:/DIR_9132017.csv, or Documents/DIR_9132017.csv, depending on what the user inputs into the textbox. I have nothing in my textbox code section at the moment, if that also gives a clearer picture about the situation.
Any help will be greatly appreciated. Thank you!
You can either use FolderBrowserDialog or can just copy/paste the path and create the directory.
Using FolderBrowserDialog
Step1 : Create Browse button (so that the user can choose the directory)
Step2 : Create Export button (Place the code to write the file here)
private void browseButton_Click(object sender, EventArgs e)
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
var folderPath = folderBrowserDialog1.SelectedPath;
textBox1.Text = folderPath;
}
}
private void exportToCsvButton_Click(object sender, EventArgs e)
{
var path = textBox1.Text;
var file = Directory.CreateDirectory(path);
var filename = "DIR_" + (DateTime.Now.ToShortDateString()) + ".csv";
File.WriteAllText(Path.Combine(path, "test.csv"), "content");
}
Using Copy/Paste
Step1 : Create Export button (User copy pastes the path. System create the directory and writes the file)
private void exportToCsvButton_Click(object sender, EventArgs e)
{
var path = textBox1.Text;
var file = Directory.CreateDirectory(path);
var filename = "DIR_" + (DateTime.Now.ToShortDateString()) + ".csv";
File.WriteAllText(Path.Combine(path, "test.csv"), "content");
}
You would use a FolderBrowserDialog for that. After adding it to your form, you can use it like this:
public void ChooseFolder()
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
folderPath = folderBrowserDialog1.SelectedPath;
}
}
Source: https://msdn.microsoft.com/en-us/library/aa984305(v=vs.71).aspx
You haven't specified whether it's WinForms or WPF, so I'm using WPF, but is should be the same in WinForms.
To select the folder, you could use FolderBrowseDialog as follows. This code should be placed inside a button or some other similar control's Click event.
if (folderBrowse.ShowDialog() == DialogResult.OK)
{
txtPath.Text = folderBrowse.SelectedPath;
}
txtPath being a TextBox your selected path displayed in. You can substitute it with a simple string variable if you don't want to use a TextBox.
And if you want the user to be able to drag-drop a folder into a TextBox, you can create a TextBox control, and in it's PreviewDragOver and Drop events, you can do the following.
private void txtPath_PreviewDragOver(object sender, DragEventArgs e)
{
e.Handled = true;
}
private void txtPath_Drop(object sender, DragEventArgs e)
{
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
if (files != null && files.Length != 0)
txtPath.Text = files[0];
}
Using both above in combination user has the ability to either select the folder he/she wants by clicking a button, drag-and-drop a folder into the TextBox, or copy-paste the folder path into the TextBox.

C# System.UnathorizedAccessException on 2nd Button Click

The button1_Click Event (Copy PDF's to new location) works perfectly when the button is clicked and the code is executed the 1st time;
however, upon clicking the button a second time (with same text box entry), it throws the following error:
System.UnauthorizedAuthorizedAccessException: Access to the path "\share\drive....
Obviously, I don't want this to be able to execute twice during a session, given the same text box entry. Before I tackle that, I would like to fix this exception error. Am I erroneously leaving the path open?
Code updated to show solution:
public static string Case_No;
namespace CEB_Process
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//===============================
// TEXT BOX ENTRY
//===============================
private void textBox1_TextChanged(object sender, EventArgs e)
{
Form1.Case_No = textBox1.Text;
}
//==============================
// CHECK if Direcotry Exists
//==============================
public void CreateIfMissing(string path)
{
if (!Directory.Exists(path))
{
DirectoryInfo di = Directory.CreateDirectory(path);
//Added
var permissions = new DirectoryInfo(path);
permissions.Attributes &= ~FileAttributes.ReadOnly;
MessageBox.Show("The directory was created successfully");
}
}
//=================================
// MOVE Violation PDF's Button Click
//==================================
private void button1_Click(object sender, EventArgs e)
{
//Declare Source path directory from text box entry
string sourcePath = string.Format(#"\\share\drive\etc{0}", Case_No);
string targetPath = string.Format(#"\\share\drive\etc{0}", Case_No);
try
{
//Call Method to Check/Create Path
CreateIfMissing(targetPath);
//Get TRAKiT Violation PDF's from source
foreach (var sourceFilePath in Directory.GetFiles(sourcePath, "*.pdf"))
{
string fileName = Path.GetFileName(sourceFilePath);
string destinationFilePath = Path.Combine(targetPath, fileName);
System.IO.File.Copy(sourceFilePath, destinationFilePath, true);
File.SetAttributes(destinationFilePath, FileAttributes.Normal);
}//End For Each Loop
MessageBox.Show("Files Copied Successfully!");
}//end try
catch (Exception x)
{
MessageBox.Show("The process failed", x.ToString());
}
}//End Button Module
}//End Namespace
}//End Class
I also had the problem I added the following line of code before and after a Copy / Delete.
File.Copy(file, dest, true);
File.SetAttributes(dest, FileAttributes.Normal);
(PS: Taken from Why is access to the path denied?)
I suppose you're using File.Copy without overwriting the selected file.
That means the file is getting copied and it's temporarily locked by OS, and then it's not open to modifications (read-only). This is the reason of your UnauthorizedAccessException.
Check if you can accessthe file first.

How do I show a directory path in a textbox when selected by the user?

First, I am using Visual Studio 2013 and coding in C# to develop a Windows Form Application. I have added the "System.IO" namespace.
I need to show a directory path in a textbox when selected by the user.
The code works correctly to where the user selects a folder from a popup
and presses the OK button, which then displays the number of files within
that folder -- but the folder path does NOT get displayed as I desired.
Code looks like this:
private void button1_Click(object sender, EventArgs e)
{
//
// This event handler was created by clicking the button in the application GUI.
//
DialogResult button1_Click = folderBrowserDialog1.ShowDialog();
if (button1_Click == DialogResult.OK)
{
//
// The user selected a folder and pressed the OK button.
// A message pops up and identifies the number of files found within that folder.
//
string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
MessageBox.Show("Files found: " + files.Length.ToString(), "Message");
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
string path;
path = folderBrowserDialog1.SelectedPath;
// folderBrowserDialog1.ShowDialog(); // NOT SURE ABOUT USING THIS!
textBox1.Text = path;
}
You could just add this to the end of your button1_Click method (inside the if block):
textBox1.Text = folderBrowserDialog1.SelectedPath;

Executing another Application with selected file using a button (C# Programming)

To start, I'm a newbie with C# Programming and I've tried googling for solutions about my problem but it seems that i cannot find one, or simply too unlucky or too blind to spot one. I'm using Microsoft Visual Studio 2005.
Anyways. I was assigned to modify/create an automated test environment input application. The said application already has a function to run/start a CANoe program with a pre-defined file or if it's already running, stop the program.
private void button1_Click(object sender, EventArgs e)
{
// Execute CANoe(Obtain CANoe application objectg)
mApp = new CANoe.Application();
mMsr = (CANoe.Measurement)mApp.Measurement;
try
{
mApp.Open("C:\\Users\\uidr3024\\Downloads\\SRLCam4T0_Validation_ControlTool\\cfg\\SVT_SRLCam4T0_025B.cfg", true, true);
}
catch (System.Exception ex)
{
System.Console.WriteLine(ex.Message);
}
}
private void button2_Click(object sender, EventArgs e)
{
// Finish CANoe
if (mApp != null) {
mApp.Quit();
}
// Release the object
fnReleaseComObject(mMsr);
fnReleaseComObject(mApp);
}
What I wanted to do now is to have an OpenFileDialog box that will show a selection of files and user will be able to browse and select any file to start the CANoe program with the selected file and not just the file path that's been input in the code along the "mApp.Open()" syntax. I've tried this:
private void button5_Click_1(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = #"C:\Users\uidr3024\Downloads\SRLCam4T0_Validation_ControlTool\cfg";
openFileDialog1.Title = "Browse Configuration Files";
openFileDialog1.CheckFileExists = true;
openFileDialog1.CheckPathExists = true;
openFileDialog1.Filter = "CANalyzer/CANoe Configuration (*.cfg)|*.cfg |All files (*.*)|*.*";
openFileDialog1.FilterIndex = 1;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = openFileDialog1.FileName;
}
}
I've tried this code that I often see in the Web and in the Tutorials but I don't know how to incorporate it with the button for running the CANoe program so that when user clicks the Open button from the Dialog Box, the file path would be shown in the textbox(optional) and/or when the user then clicks the Start CANoe, CANoe program would start with the selected .cfg file.
Am I making any sense here? Or am I doing the right thing here?
Btw, I found these... And I'm using a CANoe library for these, ofc.
#region "***** CANoe Object definition *****"
private CANoe.Application mApp = null; // CANoe Application CANoeƒAƒvƒŠƒP[ƒVƒ‡ƒ“
private CANoe.Measurement mMsr = null; // CANoe Mesurement function CANoe‘ª’è‹#”\
private CANoe.Variable mSysVar = null; // System variable ƒVƒXƒeƒ€•Ï”
private CANoe.Variable mSysVar_start = null; // System variable ƒVƒXƒeƒ€•Ï”
#endregion
I think you have done most of the hard work, unless I've missed something I think you just need something like this in your button1_Click method:
if( textBox1.Text != String.Empty && System.IO.File.Exists(textBox1.Text) )
{
// The textbox has a filename in it, use it
mApp.Open(textBox1.Text, true, true);
}
else
{
// The user hasn't selected a config file, launch with default
mApp.Open("C:\\Users\\uidr3024\\Downloads\\SRLCam4T0_Validation_ControlTool\\cfg\\SVT_SRLCam4T0_025B.cfg", true, true);
}

Categories