Can I use a declared variable or a instance of an object from one method to another?
private void OnBrowseFileClick(object sender, RoutedEventArgs e)
{
string path = null;
path = OpenFile();
}
private string OpenFile()
{
string path = null;
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Title = "Open source file";
fileDialog.InitialDirectory = "c:\\";
fileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
fileDialog.FilterIndex = 2;
fileDialog.RestoreDirectory = true;
Nullable<bool> result = fileDialog.ShowDialog();
if (result == true)
{
path = fileDialog.FileName;
}
textBox1.Text = path;
return path;
}
Now, I want to get that path and write it on excel. how will I do this, please help, I am week old in using C#.
private void btnCreateReport_Click(object sender, RoutedEventArgs e)
{
string filename = "sample.xls"; //Dummy Data
string functionName = "functionName"; //Dummy Data
string path = null;
AnalyzerCore.ViewModel.ReportGeneratorVM reportGeneratorVM = new AnalyzerCore.ViewModel.ReportGeneratorVM();
reportGeneratorVM.ReportGenerator(filename, functionName, path);
}
Thanks
Use an instance field to store the value of your variable.
Like so:
public class MyClass
{
// New instance field
private string _path = null;
private void OnBrowseFileClick(object sender, RoutedEventArgs e)
{
// Notice the use of the instance field
_path = OpenFile();
}
// OpenFile implementation here...
private void btnCreateReport_Click(object sender, RoutedEventArgs e)
{
string filename = "st_NodataSet.xls"; //Dummy Data
string functionName = "functionName"; //Dummy Data
AnalyzerCore.ViewModel.ReportGeneratorVM reportGeneratorVM = new AnalyzerCore.ViewModel.ReportGeneratorVM();
// Reuse the instance field here
reportGeneratorVM.ReportGenerator(filename, functionName, _path);
}
}
Here is a link which describes fields in much more detail than what I could.
Move the string path as a member inside your class, and remove the declaration inside the methods. that should do it
Use string path as a class level variable.
Use static private string path if you want to use it between pages.
Use private string path if you only need to use it on the current page.
you must define the variable as field in your class:
Private string path = null;
use static private string path;
Related
I'm trying to get specific data from an .ini file and display it in GridView. The .ini file is updated with information from the last cut a saw made, and every time the file is updated I want the new information displayed in a new row. The problem I keep running into is that the method I have for populating the grid viewer is repeating once every time the file is changed. Sometimes it displays the correct information twice, and sometimes it displays incorrect information once, and then the second time the correct information is displayed.
I added a check using a bool variable to try to stop this, but that hasn't stopped it from outputting twice.
using System.Text.RegularExpressions;
namespace outputViewer
{
public partial class outputViewer : Form
{
//Declare variables for filepath and create a new dictionary
private string iniFilePath;
private string vjob = "";
private string vpart = "";
private string vname = "";
private string vlength = "";
private string vwidth = "";
private string vheight = "";
private string vgrade = "";
private string vcenterLine = "";
bool populate = false; //If PopulateIniDataGrid has been called turn true
public outputViewer()
{
InitializeComponent();
}
//Watch .ini file for changes
public void Watch()
{
var watcher = new FileSystemWatcher(Path.GetDirectoryName(iniFilePath), Path.GetFileName(iniFilePath))
{
EnableRaisingEvents = true,
NotifyFilter = NotifyFilters.LastWrite
};
watcher.Changed += OnFileChanged;
}
//On file change reset bool variable and call ReadIniFile method
private void OnFileChanged(object sender, FileSystemEventArgs e)
{
populate = false;
ReadIniFile();
}
//Reads .ini file using WriteSafeReadAllLines Method, and extracts data for Output
private void ReadIniFile()
{
var iniFileLines = WriteSafeReadAllLines(iniFilePath);
var currentSection = "";
foreach (var line in iniFileLines)
{
//Code sorting through data for output
}
//Check if PopulateIniDataGridView has been called
if (!populate)
{
PopulateIniDataGridView();
populate = true;
}
}
//Set filepath of .ini file
private void setFilePathToolStripMenuItem_Click(object sender, EventArgs e)
{
//Create new openFileDialog object
var openFileDialog = new OpenFileDialog
{
//File type filters for openFileDialog and set default directory to MyDocuments
Filter = "INI files (*.ini)|*.ini|All files (*.*)|*.*",
InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
};
//If Successful
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
iniFilePath = openFileDialog.FileName;
selectedIniFileLabel.Text = iniFilePath;
}
Watch();
}
//Convert method converts mm to feet-inches-sixteenths
private void Convert(ref string imperial)
//Allow reading file when open by another application
public string[] WriteSafeReadAllLines(string path)
private void PopulateIniDataGridView()
{
//Convert metric to imperial
Convert(ref vwidth);
Convert(ref vheight);
Convert(ref vlength);
Convert(ref vcenterLine);
Invoke(new MethodInvoker(delegate
{
scOutputGridView.Rows.Add(vjob, vname, vpart, vlength, vwidth, vheight, vgrade);
}));
}
}
}
I am trying to output the file address of an item selected in a combobox. But i keep getting the Directory address of the project and not the item itself. Please help. Here is my Code:
private void comboBox1_SelectedIndexChanged_1(object sender, EventArgs e)
{
if (availableSoftDropBox.SelectedItem.Equals("Choose Your Own..."))
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
txtFlashFile.Text = openFileDialog1.FileName;
}
else
{
string fileName;
fileName = Path.GetFullPath((string)availableSoftDropBox.SelectedItem);
string fullPath = #"C:\Program Files (x86)\yeet-n . master\yeet-
master\src\yeet\System\Products\" + (fileName);
txtFlashFile.Text = fullPath;
I'm not quite sure what you want to achieve, but using FileInfo instead of Path.GetFullPath might help.
private void comboBox1_SelectedIndexChanged_1(object sender, EventArgs e)
{
const string fullPath = #"C:\Program Files (x86)\yeet-n . master\yeet-
master\src\yeet\System\Products\";
string selection = (string)availableSoftDropBox.SelectedItem;
var fileInfo = new FileInfo(fullPath + selection);
string text = fileInfo.FullName;
if (selection.Equals("Choose Your Own..."))
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
text = openFileDialog1.FileName;
}
}
txtFlashFile.Text = text;
}
My form doesn't load if I have this bit of code in it
private void Form1_Load(object sender, EventArgs e)
{
// Variables
string currentDirectory = Directory.GetCurrentDirectory();
string checkFile = ("mailingdir\\check.txt");
bool newFolder = (File.Exists(checkFile));
if (newFolder)
{
newFolder = true;
}
else
{
newFolder = false;
File.Create("mailingdir\\check.txt");
}
If I comment out the File.Create("mailingdir\\check.txt"); it loads right up.
I am just experimenting, so I think I am making a beginner mistake.
Code above works perfectly as long as path exsists. Replace "mailingdir" with dot so it will refer to location of app. Looks like there is no "mailingdir" where exe is located.
private void Form1_Load(object sender, EventArgs e)
{
string currentDirectory = Directory.GetCurrentDirectory();
string workingDirectoryPlus1 = (currentDirectory + 1);
string checkFile = (".\\check.txt");
bool newFolder = (File.Exists(checkFile));
if (newFolder)
{
newFolder = true;
}
else
{
newFolder = false;
File.Create(".\\check.txt");
}
}
Your code gives a DirectoryNotFoundException because mailingdir doesn't exist.
you must create the directory first, then the file.
Directory.CreateDirectory("mailingdir");
File.Create("mailingdir\\check.txt");
I am using this code to generate the path of a selected file:
private void LoadNewFile()
{
OpenFileDialog ofd = new OpenFileDialog();
string _xmlPath1 = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
System.Windows.Forms.DialogResult dr = ofd.ShowDialog();
if (dr == DialogResult.OK)
{
userSelectedFilePath = ofd.FileName;
}
}
private void tbFilePath_TextChanged(object sender, EventArgs e)
{
}
Before i used this code to pass the data:
private void btn_compare_Click(object sender, EventArgs e)
{
string x1 = System.IO.File.ReadAllText(#"C:\Users", Encoding.UTF8);
How do i modify it that instead of x1 that takes the path manually, i need it to be equal to xmlPath1 , so string x1 = xmlPath1
Just change _xmlPath1 to a field and you can access it from any method within your class.
Example:
public class MyClass
{
protected String _xmlPath1;
' insert your methods here
}
If your methods are not in the same class you have to widen the scope of _xmlPath1 even more.
EDIT: Changed VB.net syntax to C#
1 )If userSelectedFilePath is a private field you can use it in btn_compare_Click
2 )If it is a local variable ,make it a private field and then see 1
3)Make the the method return the file
private string LoadNewFile()
{
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 use it (you must add validation logic)
private void btn_compare_Click(object sender, EventArgs e)
{
string x1 = System.IO.File.ReadAllText(LoadNewFile(), Encoding.UTF8);
}
Option 3 is the best way so you can avoid the extra field and make btn_compare_Click independent from the rest of the code.
In that case you should also give it a better name like GetFileToRead()
Hey there i started learning C# a few days ago and I'm trying to make a program that copies and pastes files (and replaces if needed) to a selected directory but I don't know how to get the directory and file paths from the openfiledialog and folderbrowserdialog
what am I doing wrong?
Here's the code:
namespace filereplacer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void direc_Click(object sender, EventArgs e)
{
string folderPath = "";
FolderBrowserDialog directchoosedlg = new FolderBrowserDialog();
if (directchoosedlg.ShowDialog() == DialogResult.OK)
{
folderPath = directchoosedlg.SelectedPath;
}
}
private void choof_Click(object sender, EventArgs e)
{
OpenFileDialog choofdlog = new OpenFileDialog();
choofdlog.Filter = "All Files (*.*)|*.*";
choofdlog.FilterIndex = 1;
choofdlog.Multiselect = true;
choofdlog.ShowDialog();
}
private void replacebtn_Click(object sender, EventArgs e)
{
// This is where i'm having trouble
}
public static void ReplaceFile(string FileToMoveAndDelete, string FileToReplace, string BackupOfFileToReplace)
{
File.Replace(FileToMoveAndDelete, FileToReplace, BackupOfFileToReplace, false);
}
}
For OpenFileDialog:
OpenFileDialog choofdlog = new OpenFileDialog();
choofdlog.Filter = "All Files (*.*)|*.*";
choofdlog.FilterIndex = 1;
choofdlog.Multiselect = true;
if (choofdlog.ShowDialog() == DialogResult.OK)
{
string sFileName = choofdlog.FileName;
string[] arrAllFiles = choofdlog.FileNames; //used when Multiselect = true
}
For FolderBrowserDialog:
FolderBrowserDialog fbd = new FolderBrowserDialog();
fbd.Description = "Custom Description";
if (fbd.ShowDialog() == DialogResult.OK)
{
string sSelectedPath = fbd.SelectedPath;
}
To access selected folder and selected file name you can declare both string at class level.
namespace filereplacer
{
public partial class Form1 : Form
{
string sSelectedFile;
string sSelectedFolder;
public Form1()
{
InitializeComponent();
}
private void direc_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
//fbd.Description = "Custom Description"; //not mandatory
if (fbd.ShowDialog() == DialogResult.OK)
sSelectedFolder = fbd.SelectedPath;
else
sSelectedFolder = string.Empty;
}
private void choof_Click(object sender, EventArgs e)
{
OpenFileDialog choofdlog = new OpenFileDialog();
choofdlog.Filter = "All Files (*.*)|*.*";
choofdlog.FilterIndex = 1;
choofdlog.Multiselect = true;
if (choofdlog.ShowDialog() == DialogResult.OK)
sSelectedFile = choofdlog.FileName;
else
sSelectedFile = string.Empty;
}
private void replacebtn_Click(object sender, EventArgs e)
{
if(sSelectedFolder != string.Empty && sSelectedFile != string.Empty)
{
//use selected folder path and file path
}
}
....
}
NOTE:
As you have kept choofdlog.Multiselect=true;, that means in the OpenFileDialog() you are able to select multiple files (by pressing ctrl key and left mouse click for selection).
In that case you could get all selected files in string[]:
At Class Level:
string[] arrAllFiles;
Locate this line (when Multiselect=true this line gives first file only):
sSelectedFile = choofdlog.FileName;
To get all files use this:
arrAllFiles = choofdlog.FileNames; //this line gives array of all selected files
Use the Path class from System.IO. It contains useful calls for manipulating file paths, including GetDirectoryName which does what you want, returning the directory portion of the file path.
Usage is simple.
string directoryPath = System.IO.Path.GetDirectoryName(choofdlog.FileName);
you can store the Path into string variable like
string s = choofdlog.FileName;
To get the full file path of a selected file or files, then you need to use FileName property for one file or FileNames property for multiple files.
var file = choofdlog.FileName; // for one file
or for multiple files
var files = choofdlog.FileNames; // for multiple files.
To get the directory of the file, you can use Path.GetDirectoryName
Here is Jon Keet's answer to a similar question about getting directories from path
Create this class as Extension:
public static class Extensiones
{
public static string FolderName(this OpenFileDialog ofd)
{
string resp = "";
resp = ofd.FileName.Substring(0, 3);
var final = ofd.FileName.Substring(3);
var info = final.Split('\\');
for (int i = 0; i < info.Length - 1; i++)
{
resp += info[i] + "\\";
}
return resp;
}
}
Then, you could use in this way:
//ofdSource is an OpenFileDialog
if (ofdSource.ShowDialog(this) == DialogResult.OK)
{
MessageBox.Show(ofdSource.FolderName());
}
Your choofdlog holds a FileName and FileNames (for multi-selection) containing the file paths, after the ShowDialog() returns.
A primitive quick fix that works.
If you only use OpenFileDialog, you can capture the FileName, SafeFileName, then subtract to get folder path:
exampleFileName = ofd.SafeFileName;
exampleFileNameFull = ofd.FileName;
exampleFileNameFolder = ofd.FileNameFull.Replace(ofd.FileName, "");
I am sorry if i am late to reply here but i just thought i should throw in a much simpler solution for the OpenDialog.
OpenDialog ofd = new OpenDialog();
var fullPathIncludingFileName = ofd.Filename; //returns the full path including the filename
var fullPathExcludingFileName = ofd.Filename.Replace(ofd.SafeFileName, "");//will remove the filename from the full path
I have not yet used a FolderBrowserDialog before so i will trust my fellow coders's take on this. I hope this helps.
String fn = openFileDialog1.SafeFileName;
String path = openFileDialog1.FileName.ToString().Replace(fn, "");