How do I save the last folder selected by the user? - c#

I have this and this only saves the last folder used when the user closes the application and re-opens it.
private void btnBrowse_Click(object sender, EventArgs e)
{
Properties.Settings.Default.Reload();
fbFolderBrowser.SelectedPath = AppVars.LastSelectedFolder;
if (fbFolderBrowser.ShowDialog() == DialogResult.OK)
{
Properties.Settings.Default.LastSelectedFolder = fbFolderBrowser.SelectedPath.ToString();
Properties.Settings.Default.Save();
}
}
Every time the user selects a folder, I want to save that path. Then, when he clicks the browse button again, I want the default path to be his last selection.
The above is not working. It only saves the last path selected and goes back to it only if I restart the app. How would I go about saving the last path in the same app session?

You need to reload the settings:
Properties.Settings.Default.Reload();
Note that this only works when not running in Debug mode (AFAIK).

I'm gonna post my code here, because none of the answers I had seen addressed all the issues. This will save the location and re-load the settings for a file Browse dialog (file and folder browse dialogs are slightly different when getting path)... the answers above seem to be for the session only(?). Updated with new method to avoid config settings be lost with an update of clickonce app...
Code:
public class ConfigSettingsDictionary
{
public Dictionary<String, String> ConfigSettings = new Dictionary<String, String>();
}
ConfigSettingsDictionary MyConfigurationSettings = new ConfigSettingsDictionary();
private void SaveConfig()
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\YOUR_APP_NAME_PLUS_UNIQUE_VALUE.config"))
{
foreach (var pair in MyConfigurationSettings.ConfigSettings)
{
sw.WriteLine(pair.Key + "=" + pair.Value);
}
}
}
private void LoadConfig()
{
if (System.IO.File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\YOUR_APP_NAME_PLUS_UNIQUE_VALUE.config"))
{
var settingdata = System.IO.File.ReadAllLines(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\YOUR_APP_NAME_PLUS_UNIQUE_VALUE.config");
for (var i = 0; i < settingdata.Length; i++)
{
var setting = settingdata[i];
var sidx = setting.IndexOf("=");
if (sidx >= 0)
{
var skey = setting.Substring(0, sidx);
var svalue = setting.Substring(sidx + 1);
if (!MyConfigurationSettings.ConfigSettings.ContainsKey(skey))
{
MyConfigurationSettings.ConfigSettings.Add(skey, svalue);
}
}
}
}
}
private void UpdateConfig(Dictionary<String, String> keyvaluepairs)
{
foreach (var pair in keyvaluepairs)
{
if (!MyConfigurationSettings.ConfigSettings.ContainsKey(pair.Key))
{
MyConfigurationSettings.ConfigSettings.Add(pair.Key, pair.Value);
}
else
{
MyConfigurationSettings.ConfigSettings[pair.Key] = pair.Value;
}
}
}
then I use it like this (this saves the folder chosen in a file browse dialog and also the file chosen):
string lastused = "";
if (MyConfigurationSettings.ConfigSettings.ContainsKey("openFileDialog2_last_used"))
{
MyConfigurationSettings.ConfigSettings.TryGetValue("openFileDialog2_last_used", out lastused);
}
if (lastused != "")
{
openFileDialog2.InitialDirectory = lastused;
}
else
{
openFileDialog2.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
}
string filestring = "";
if (template_filename == "")
{
try
{
if (openFileDialog2.ShowDialog() == DialogResult.OK)
{
filestring = openFileDialog2.FileName;
String chosenPath = Path.GetDirectoryName(openFileDialog2.FileName);
Dictionary<String, String> settings_to_save = new Dictionary<String, String>();
settings_to_save.Add("openFileDialog2_last_used", chosenPath);
settings_to_save.Add("openFileDialog2_last_used_template_file", filestring);
UpdateConfig(settings_to_save);
}
else return;
}
catch (Exception ex)
{
MessageBox.Show("There was an error.", "Invalid File", MessageBoxButtons.OK);
return;
}
private void YOURFORMNAME_Load(object sender, EventArgs e)
{
// Load configuration file
LoadConfig();
}
private void YOURFORMNAME_FormClosing(object sender, FormClosingEventArgs e)
{
// Save configuration file
SaveConfig();
}

Related

c# forms multiple option using radio buttons and checkboxes

I am a beginner coder in c# and i am having an issue with making multiple choices. basically i want the user to upload a text file with a list of URLs to be tested, (which i have working), then i want the user to be able to select which browser/browsers to perform the test with using the check boxes. and also if the test can run normally or using headless browser config. I have normal tests and headless tests working, but what i can't work out is how to make it so that a user can select which browser to perform the test with and make it so that it then runs it as a normal or headless test. I have attached an image of the form i have created and my form code(i have removed any non-essential parts). if for instance the user wants to select multiple browsers to run the test the code doesn't launch. i hope i have made sense of what i need help with but i have really pushed my coding knowledge to extremes with this and am at wits end
public partial class AtpTester2 : Form
{
private IWebDriver chromeDriver;
private IWebDriver foxDriver;
private IWebDriver edgeDriver;
OpenFileDialog openFileDialog = new OpenFileDialog();
public AtpTester2()
{
InitializeComponent();
TopMost = true;
}
private void StartBtn_Click(object sender, EventArgs e)
{
if (NormalTestRBtn.Checked == true)
{
Console.WriteLine("Normal Chrome Test Selected");
foreach (string url in LSlistBox.Items)
{
//check if URL is valid
Uri uriResult;
bool result = Uri.TryCreate(url, UriKind.Absolute, out uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);
//if valid URL call your OpenBrowsers method
if (result)
{
OpenBrowsers(url);
AccChromeTest();
CloseBrowser();
}
}
}
else if (HeadlessTestRBtn.Checked == true)
{
Console.WriteLine("Headless Test Selected");
foreach (string url in LSlistBox.Items)
{
//check if URL is valid
Uri uriResult;
bool result = Uri.TryCreate(url, UriKind.Absolute, out uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);
//if valid URL call your OpenBrowsers method
if (result)
{
OpenHeadlessBrowsers(url);
AccChromeTest();
CloseBrowser();
}
}
}
else
{
Console.WriteLine("It won't work!!!!!");
SystemSounds.Beep.Play();
MessageBox.Show("Select a test option first", "Oops", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
private void UrlFilePickerBtn_Click(object sender, EventArgs e)
{
var filePath = string.Empty;
openFileDialog.InitialDirectory = Application.StartupPath;
openFileDialog.Filter = "txt files (*.txt)|*.txt|All Files (*.*)|*.*";
openFileDialog.FilterIndex = 2;
openFileDialog.RestoreDirectory = true;
if(openFileDialog.ShowDialog() == DialogResult.OK)
{
filePath = openFileDialog.FileName;
var fileStream = openFileDialog.OpenFile();
StreamReader reader = new StreamReader(fileStream);
{
string line;
while ((line = reader.ReadLine()) != null) {
LSlistBox.Items.Add(line);
}
}
}
}
private void ExitBtn_Click(object sender, EventArgs e)
{
Close();
}
private void ClrLSBoxBtn_Click(object sender, EventArgs e)
{
LSlistBox.Items.Clear();
}
//
// Any other functions
//
public void OpenBrowsers(string URL)
{
Console.WriteLine("Normal Button Starting Browsers");
if (ChromeChkBox.Checked)
{
chromeDriver = DriverClass.GetDriver("Chrome");
chromeDriver.Navigate().GoToUrl(URL);
chromeDriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(20);
}
if (FirefoxChkBox.Checked)
{
foxDriver = DriverClass.GetDriver("Firefox");
foxDriver.Navigate().GoToUrl(URL);
foxDriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(20);
}
if(EdgeChkBox.Checked)
{
edgeDriver = DriverClass.GetDriver("Edge");
edgeDriver.Navigate().GoToUrl(URL);
edgeDriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(20);
}
}
public void OpenHeadlessBrowsers(string URL)
{
Console.WriteLine("Headless Button Starting Browsers");
chromeDriver = DriverClass.GetDriver("Chrome Headless");
chromeDriver.Navigate().GoToUrl(URL);
chromeDriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(20);
}
public void AccChromeTest()
{
Console.WriteLine("AccTest started for small test");
string title = chromeDriver.Title;
string url = chromeDriver.Url;
Console.WriteLine(title + " :: " + url);
AxeResult axeResult = new AxeBuilder(chromeDriver).WithTags("wcag2a", "wcag2aa").Analyze();
//Creates the Chrome HTML report and sends it the reports folder
Directory.CreateDirectory(Application.StartupPath + "\\Reports");
string path = Path.Combine(Application.StartupPath + "\\Reports", "AccReport.html");
chromeDriver.CreateAxeHtmlReport(axeResult, path);
Console.WriteLine("Report Printed");
}
public void CloseBrowser()
{
if (ChromeChkBox.Checked)
{
chromeDriver.Quit();
Console.WriteLine("Chrome Browser Closed");
}
if(FirefoxChkBox.Checked)
{
foxDriver.Quit();
Console.WriteLine("Firefox Browser Closed");
}
if (EdgeChkBox.Checked)
{
edgeDriver.Quit();
Console.WriteLine("Edge Browser Closed");
}
}
}
}

C# Inputbox cancel button does not work

I have below code on my browse button.
How can I write code for inputbox cancel button.
private void btnbrowse_Click(object sender, EventArgs e)
{
String sf_no = Microsoft.VisualBasic.Interaction.InputBox(
"You are uploading File For SF NO. ", "Information", def, -1, -1);
ofd.ShowDialog();
ofd.Multiselect = true;
string[] result = ofd.FileNames;
foreach (string y in result)
{
String path = y.Substring(0, y.LastIndexOf("\\"));
String filename = y.Substring(y.LastIndexOf("\\"));
string[] row = new string[] { sf_no,path, filename };
dataGridView2.Rows.Add(row);
}
}
On Cancellation of InputBox, the return value is an empty string, so your code would be
if (sf_no!="")
{
//ok stuff here, including the showdialog logic as shown below
}
{
//cancel stuff here
}
Since ofd.ShowDialog can also be cancelled your code should be :
if (ofd.ShowDialog()==DialogResult.OK)
{
//do stuff on OK button
}
else
{
//do stuff on Cancel button
}
Either call ofd.Multiselect = true; before calling ShowDialog() or set it on Properties box if you'll always have Multiselect anyway.
Thus, your new code are now :
private void btnbrowse_Click(object sender, EventArgs e)
{
String sf_no = Microsoft.VisualBasic.Interaction.InputBox("You are uploading File For SF NO. ", "Information", def, -1, -1);
if (sf_no!="") //we got the sf_no
{
ofd.Multiselect = true;
if (ofd.ShowDialog()==DialogResult.OK)//user select file(s)
{
string[] result = ofd.FileNames;
foreach (string y in result)
{
String path = System.IO.Path.GetDirectoryName(y);
String filename = System.IO.Path.GetFileName(y);
string[] row = new string[] { sf_no,path, filename };
dataGridView2.Rows.Add(row);
}
}
else
{
//handle what happen if user click cancel while selecting file
}
}
else
{
//handle what happen if user click cancel while entering SF NO
}
}

How do I implement error checking

Hi guys I have this app that does printing based on items on a listbox.
by commatching those items with that in a directory :\slim\slimyyyy
I want to put an "ERROR CHECKING" that would give me a message that in item
on the listbox is not present in the directory .
For instance if there are 8 items or more is not in the said directory give message with the item thats not in the directory.
Find below is my code ,but my try catch does nothing.Any help is very welcome
Thanks in advance.
{
//var printList = new List();
try
{
var printList = new List();
string dir = #"C:\slim\slimyyyy";
if (Directory.Exists(dir))
{
string[] pdf_specFiles = Directory.GetFiles(dir);
if (pdf_specFiles.Length > 0)
{
foreach (object item in listBox1.Items)
{
foreach (string file in pdf_specFiles)
{
string fileName = Path.GetFileName(file);
if (fileName == item.ToString())
{
printList.Add(Path.GetFullPath(file));
}
}
}
foreach (string file in printList)
{
PrintDocument(file);
System.Threading.Thread.Sleep(10000); // wait 10 second say
Application.DoEvents(); // keep UI responsive if Windows Forms app
}
}
}
}
catch (Exception)
{
MessageBox.Show("You are missing Item(s).", "ERROR");
}
}>
Here's the new solution:
- Please put using System.Linq on top of form
private void Form1_Load(object sender, System.EventArgs e)
{
const string directoryPath = #"C:\slim\slimyyyy";
var printList = new List<string>();
foreach (string item in listBox1.Items)
{
var currentFilePath = Path.Combine(directoryPath, item);
if (File.Exists(currentFilePath))
{
printList.Add(item);
}
}
if (!printList.Any())
{
MessageBox.Show("File doesn't exist");
return;
}
foreach (string file in printList)
{
PrintDocument(file);
// Why you want to wait?? Let it print.
}
}

c# ListView - got "the path is not a legal form" while implementing MouseDoubleClick() method

I'm very new to C#. I'm populating a File Explorer using C#. What i want to do now is implementing the listView1_MouseDoubleClick() method so that when I double-click in a sub folder, the current listView will be cleared then it will display files and folders in that subfolders (like what Windows Explorer does). Here's my code:
private void listView1_MouseDoubleClick(object sender, MouseEventArgs e)
{
for (int i = 0; i < listView1.Items.Count; i++)
{
if (listView1.Items[i].Selected == true)
{
string path = listView1.Items[i].Name;
comboBox1.Text = path;
listView1.Items.Clear();
LoadFilesAndDir(path);
}
}
}
private void LoadFilesAndDir(string address)
{
DirectoryInfo di = new DirectoryInfo(address);
try
{
foreach (FileInfo fi in di.GetFiles())
{
listView1.Items.Add(fi.Name);
}
try
{
foreach (DirectoryInfo listd in di.GetDirectories())
{
listView1.Items.Add(listd.FullName, listd.Name, 0);
}
}
catch (Exception e1)
{
}
}
catch (Exception e1)
{
}
}
But it failed to run. When I debug this error step by step, I found out that after this statement: path = listView1.Items[i].Name; the path variable's value is "". So i guess that the reason which let to the error. But I don't know how to fix that... Could you guys help me with this ? Thanks a lot in advanced !
Make sure that you declare the string 'path' first
string path = "";
Then insert this code:
private void listView1_MouseDoubleClick(object sender, EventArgs e)
{
for (int i = 0; i < listView1.Items.Count; i++)
{
if (listView1.Items[i].Selected == true)
{
path = Convert.ToString(listView1.Items[i]);
// This replaces the part "List View Item: {"
path = path.Replace("ListViewItem: {", "");
// This replaces the part "}"
path = path.Replace("}", "");
comboBox1.Text = path;
listView1.Items.Clear();
LoadFilesAndDir(path);
}
}
}
The code is a bit long, but it works!

working with StreamReader and text files

I want to put a test loop on the button click event. When I click this button, it reads the contents of the text file, but I want it to pop up an error message showing “unable to read file”, if it’s not a text file....
This is my code
private void button3_Click(object sender, EventArgs e)
{
StreamReader sr = new StreamReader(textBox1.Text);
richTextBox1.Text = sr.ReadToEnd();
sr.Close();
}
How can I go about it?
A few if-statements and the namespace System.IO will do it
string filename = textBox1.Text;
if (Path.GetExtension(filename).ToLower()) == ".txt") {
if (File.Exists(filename)) {
// Process the file here
} else {
MessageBox.Show("The file does not exist");
}
} else {
MessageBox.Show("Not a text file");
}
Not the best code, but it should work. Ideally you would separate the logic into two methods, a function to check the file exists and is a text file (returning a bool), another to read the contents if the check function returned true and populate the textbox with the contents.
EDIT: This is better:
private void button3_Click(object sender, EventArgs e)
{
string filePath = textBox1.Text;
bool FileValid = ValidateFile(filePath);
if (!IsFileValid)
{
MessageBox.Show(string.Format("File {0} does not exist or is not a text file", filePath));
}
else
{
textbox2.Text = GetFileContents(filePath);
}
}
private bool IsFileValid(string filePath)
{
bool IsValid = true;
if (!File.Exists(filePath))
{
IsValid = false;
}
else if (Path.GetExtension(filePath).ToLower() != ".txt")
{
IsValid = false;
}
return IsValid;
}
private string GetFileContents(string filePath)
{
string fileContent = string.Empty;
using (StreamReader reader = new StreamReader(filePath))
{
fileContent = reader.ReadToEnd();
}
return fileContent;
}

Categories

Resources