I am unable to update my C# string variable - c#

New to C#. I am trying to create a WinForms application to run different batch files. Due to the different path of the batch files for everyone (depending on where they store it), I am planning to let user select their path when they first start the WinForms.
I have tried several ways to save the path into a variable, then plan to use the variable to with Process.Start
Below are a part of my codes:
private void buttonTest_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
string filePath = "a";
if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string filePath = openFileDialog.FileName;
labelTest.Text = filePath;
Properties.Settings.Default["filePath"] = filePath;
Properties.Settings.Default.Save();
}
}
I'm constantly receiving an error in my if statement, cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter.
May I know what am I doing wrong? Appreciate any advices!

Related

How can I pass a file/file path from one Button_Click event to another in C#?

I have a fileupload control (FileUpload1) in my webform which I use to load an excel file. I use a button called btn_open to display it in a gridview on click.
I also save the file using FileUpload1.SaveAs() method in a server folder.
Now I have another button called btn_edit which on click needs to use the same
file that I just loaded to do another set of operations.
How do I pass this file/file path from btn_open_Click to btn_edit_Click? I do not want to specify the exact location on the code. There will be multiple times I will open new excel files so I don't want to specify the file path to the server for every new file.This needs to happen programatically. Also, I want to avoid using Interop if its possible.
The following code snippet might make things more clear as to what I want to do.
protected void btn_open_Click(object sender, EventArgs e)
{
string fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName);
if (fileExtension.ToLower() == ".xlsx" || fileExtension.ToLower() == ".xls")
{
string path = Path.GetFileName(FileUpload1.FileName); //capture the file name of the file I have uploaded
path = path.Replace(" ", ""); // if there is any spacing between the file name it will remove it
FileUpload1.SaveAs(Server.MapPath("~/ExcelFile/") + path); //saves to Server folder called ExcelFile
String ExcelPath = Server.MapPath("~/ExcelFile/") + path; // Returns the physical file path that corresponds to the specified virtual path.
.
.
*code to display it in gridview*
.
.
}
else
{
Console.Writeline("File type not permissible");
}
}
protected void btn_edit_Click(object sender, EventArgs e)
{
//HOW DO I PASS THE ABOVE FILE HERE PROGRAMATICALLY WITHOUT SPECIFYING IT'S EXACT LOCATION ON THE SERVER??
}
Using Session variable helped me solve my problem. Hopefully it will be helpful to other people who might encounter similar issue.
On the first button (in my case btn_open_Click), add:
Session["myXlsPath"] = ExcelFilePath;
Note: "myXlsPath" is just a name I created for my Session variable. ExcelFilePath is the path of my excel file that I want to pass to the other button.
On the button you want to pass the file path to (in my case btn_edit_Click), add:
string ExcelFilePath = (string)Session["myXlsPath"];

Transfer a textfile to another folder

I am quite confused as to why my code isn't working. I wanted to transfer a textfile that I have into another folder. Here is my code:
private void transferButton_Click(object sender, EventArgs e)
{
string acct = #"C:\\Users\\Accounting\\TicketQueue\\";
string reg = #"C:\\Users\\Registrar\\TicketQueue\\";
if (office == "Registrar")
{
File.Move(reg, acct);
}
else {
File.Move(acct, reg);
}
cleanUp();
}
The office variable is determined beforehand. (Registrar or Accounting)
The cleanup() method is used to clear the entire form and prompt a message that successfully transfers the file.
Everytime I click the button an error displays saying:
Additional information: Could not find file 'C:\Users\Accounting\TicketQueue\'.
You have not actually specified a file name, just a folder location. Do you know the name of the file, or are you trying to transfer the entire folder's contents? Code would need to be something like:
string acct = #"C:\\Users\\Accounting\\TicketQueue\\from.txt";
string reg = #"C:\\Users\\Registrar\\TicketQueue\\to.txt";

Reading the correct directory

I've tested the code and the directory gets the correct input, but for some reason it can't find it. Is there something I'm missing why I can't find any directory?
Here is my code pretty simplistic as of right now.
public partial class Form1 : Form
{
string fileName;
string dirName;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
dirName = textBox1.Text;
fileName = textBox2.Text;
if (System.IO.Directory.Exists(dirName))
{
if (System.IO.File.Exists(fileName))
{
System.IO.File.Delete(fileName);
}
else
{
MessageBox.Show("Invalid Directory or File Name");
}
}
}
That's because I guess you're passing the directory path by an input control in this way "C:/examplePath/" and it should be declared in this way "C:\\examplePath" because the escape characters, and probably you'll get another error further because when you're asking for a file's existence, you must to declare it concatenating directory path plus filename (and its extension).
so the final string should be like this "c:\\exampleDir\\examplefile.ext"
or simply you should try:
dirName = string.Format("#{0}", textBox1.Text);
fullPathFile = string.Format("{0}/{1}", dirName, textBox2.Text);
And then you use "fullPathFile" instead of "fileName" variable.
Don't forget to debug your application for making sure what's the string values.
Based on your code, it appears fileName and dirName come from two different textbox controls. And you also dont do any sort of combining the file path (or so it appears). So when you call Directory.Exists() it makes sense that this would work but it can't find the file. When you use File.Exists() you need to pass in not only the file name but also the directory where its located. To do this use the Path.Combine() method.
if (System.IO.Directory.Exists(dirName))
{
string filePath = System.IO.Path.Combine(dirName, fileName);
if (System.IO.File.Exists(filePath))
{
System.IO.File.Delete(filePath);
}
else
{
MessageBox.Show("Invalid Directory or File Name");
}
}

Directory could not be found

I have recently started to get an error which states my directory can not be found I have tried a number of ways to solve this but have yet to find a solution.
The method should allow the user to select an image for their computer and add it to a folder called images inside the applications folder structure. The problem is that when using the File.copy(imageFilename, path); it throws the error. I have tried changing the path and you will see from the code snip it. It is even doing it when the program itself has passed the file path for the application and is still throwing me the error.
this is the method.
private void btnImageUpload_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog imageFile = new OpenFileDialog();
imageFile.InitialDirectory = #"C:\";
imageFile.Filter = "Image Files (*.jpg)|*.jpg|All Files(*.*)|*.*";
imageFile.FilterIndex = 1;
if (imageFile.ShowDialog() == true)
{
if(imageFile.CheckFileExists)
{
string path = AppDomain.CurrentDomain.BaseDirectory;
System.IO.File.Copy(imageFile.FileName, path);
}
}
}
I am using VS2013 and have included the using Microsoft.win32
Any further information needed please ask.
Thanks
There are 2 things need to be taken into consideration
private void btnImageUpload_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog imageFile = new OpenFileDialog();
imageFile.InitialDirectory = #"C:\";
imageFile.Filter = "Image Files (*.jpg)|*.jpg|All Files(*.*)|*.*";
imageFile.FilterIndex = 1;
if (imageFile.ShowDialog() == true)
{
if(imageFile.CheckFileExists)
{
string path = AppDomain.CurrentDomain.BaseDirectory; // You wont need it
System.IO.File.Copy(imageFile.FileName, path); // Copy Needs Source File Name and Destination File Name
}
}
}
string path = AppDomain.CurrentDomain.BaseDirectory; You won need this because the default directory is your current directory where your program is running.
Secondly
System.IO.File.Copy(imageFile.FileName, path); Copy Needs Source File Name and Destination File Name so you just need to give the file name instead of path
so your updated code will be
private void btnImageUpload_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog imageFile = new OpenFileDialog();
imageFile.InitialDirectory = #"C:\";
imageFile.Filter = "Image Files (*.jpg)|*.jpg|All Files(*.*)|*.*";
imageFile.FilterIndex = 1;
if (imageFile.ShowDialog() == true)
{
if(imageFile.CheckFileExists)
{
System.IO.File.Copy(imageFile.FileName, SomeName + ".jpg"); // SomeName Must change everytime like ID or something
}
}
}
I'm not sure if that's the problem, but the File.Copy method expects a source file name and a target file name, not a source file name and directory: https://msdn.microsoft.com/en-us/library/c6cfw35a(v=vs.110).aspx
So, to make this work, in your case you'd have to do something like the following (namespaces omitted):
File.Copy(imageFile.FileName, Path.Combine(path, Path.GetFileName(imageFile.FileName));
Note that this will fail if the destination file exists, to overwrite it, you need to add an extra parameter to the Copy method (true).
EDIT:
Just a note, the OpenFileDialog.CheckFileExists does not return a value indicating if the selected file exists. Instead, it is a value indicating whether a file dialog displays a warning if the user specifies a file name that does not exist. So instead of checking this property after the dialog is closed, you should set it to true before you open it (https://msdn.microsoft.com/en-us/library/microsoft.win32.filedialog.checkfileexists(v=vs.110).aspx)

Dynamic File Paths

Suppose I had a particular directory on C# in the following format:
#"C:\blabla\bla\0.0.1.63\blabla.png";
The "0.0.1.63" changes occasionally due to updates to the software and so on.
I want to know how I can assign a "..\" - similar effect for that particular directory to be dynamic. Because I do not know the update sequence.
So, how do I make it so that the directory stays the same, while that particular part of the directory (0.0.1.63) is an "unknown" directory.
You can use the DirectoryInfo.EnumerateDirectories and the DirectoryInfo.EnumerateFileSystemInfos methods to find your file, you could then strip the filename from the FileInfo objects FullName and use the result. Something like this should work.
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.InitialDirectory = getPath();
openFileDialog1.ShowDialog();
}
private string getPath()
{
DirectoryInfo di = new DirectoryInfo(#"C:\blabla\bla\");
foreach (var d in di.EnumerateDirectories())
{
foreach(var fi in d.EnumerateFileSystemInfos())
{
if (fi.Name == "blabla.png")
{
return fi.FullName.Replace(fi.Name,"");
}
}
}
return di.FullName ;
}

Categories