how do I recall a string from a different function? - c#

I am having trouble calling the string "rlist" from:
public void main()
{
string rlist;
if (radioButton1.Checked)
textBox1.Enabled = false;
textBox1.ReadOnly = true;
rlist = "text";
}
to
public void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openFile = new OpenFileDialog();
openFile.Filter = "WTF Files (*.wtf)|*.wtf";
openFile.Title = "Please Pick your realmlist file:";
if (openFile.ShowDialog() == DialogResult.Cancel)
return;
try
{
textBox5.Text = openFile.FileName;
string file = openFile.FileName;
TextWriter rlist_writer = new StreamWriter (openFile.FileName);
rlist_writer.WriteLine(rlist);
rlist_writer.Close();
}
catch (Exception)
{
MessageBox.Show("Error opening file", "File Error",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
I get the error on this line:
rlist_writer.WriteLine(rlist);
is it possible to call a string from one function and send it to the other with the same value it had in the function it was originally pulled from?

By the sounds of your question,
Your string is local to your main function.
So judging by your method names and knowledge of winforms(presumed again)
you need to make your string class level
string rlist;
public void main()
{
rlist = "yay"
public void button1_Click(object sender, EventArgs e)
{
someText = rlist;
As it currently stands you are not able to, as temporary (local) variables will be cleaned through garbage collection when you leave the method
Edit
You may wish to review this also
try
{
textBox5.Text = openFile.FileName;
using(TextWriter rlist_writer = new StreamWriter (openFile.FileName))
{
rlist_writer.WriteLine(rlist);
}
}

You can define that variable in your class scope, then if you call that variable in your button_click event, it will maintain the same value as in your main method.

Related

Savefiledialog locked file, change file name

How to keep the savefilediallog open when you write to a file which is in use by an other program so that you can change the file name and try to save again?
private void button1_Click_2(object sender, EventArgs e)
{
Cursor.Current = Cursors.WaitCursor;
CsvExport = Class_ExportData.DataTableToCSV(datatabelControle, csvSCheidingteken);
Cursor.Current = Cursors.Default;
saveFileDialog1.OverwritePrompt = true;
saveFileDialog1.Filter = "Komma gescheiden waarden (*.csv)|*.csv|Tekst bestanden (*.txt)|*.txt|Alle formaten (*.*)|*.*";
saveFileDialog1.DefaultExt = "csv";
saveFileDialog1.AddExtension = true;
saveFileDialog1.ShowDialog();
}
private void saveFileDialog1_FileOk(object sender, CancelEventArgs e)
{
try
{
string name = saveFileDialog1.FileName; // Get file name.
File.WriteAllText(name, CsvExport); // Write to the file name selected.
}
catch (Exception ex)
{
//file is locked, how to get back to the open save file dialog ???
}
}
Try this. Move the code associated with opening the saveFileDialog1 into its own function and invoke that function from button1_Click:
private void button1_Click_2(object sender, EventArgs e)
{
Cursor.Current = Cursors.WaitCursor;
CsvExport = Class_ExportData.DataTableToCSV(datatabelControle, csvSCheidingteken);
Cursor.Current = Cursors.Default;
ShowSaveFileDialog();
}
private void ShowSaveFileDialog()
{
saveFileDialog1.OverwritePrompt = true;
saveFileDialog1.Filter = "Komma gescheiden waarden (*.csv)|*.csv|Tekst bestanden (*.txt)|*.txt|Alle formaten (*.*)|*.*";
saveFileDialog1.DefaultExt = "csv";
saveFileDialog1.AddExtension = true;
saveFileDialog1.ShowDialog();
}
EDIT: On further consideration, I don't think you want/need the loop here, so I've removed it. You still want to invoke the ShowSaveFileDialog method here in case of exceptions, though:
private void saveFileDialog1_FileOk(object sender, CancelEventArgs e)
{
try
{
string name = saveFileDialog1.FileName; // Get file name.
File.WriteAllText(name, CsvExport); // Write to the file name selected.
return;
}
catch (Exception ex)
{
//file is locked, how to get back to the open save file dialog ???
// maybe display an error message here so that the user knows why they're about to see the dialog again.
}
ShowSaveFileDialog();
}
Technically, this can probably lead to a StackOverflowException if the user tries repeatedly (and I mean thousands of times) to retry the save after an exception, but that's pretty unlikely.

How to load paths into ListBox and afterwards start the file per selected Index

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void cmdAdd_Click(object sender, EventArgs e)
{
OpenFileDialog OP = new OpenFileDialog();
OP.Title = "Please select the wanted .exe";
string FileName = String.Empty;
string PathName = String.Empty;
OP.InitialDirectory = #"C:\Users\" + Environment.UserName.ToString() + #"\Desktop";
OP.DefaultExt = ".exe";
OP.Filter = "Game executable (*.exe) |*.exe";
DialogResult Ergebnis = OP.ShowDialog();
if (Ergebnis == DialogResult.OK)
{
FileInfo File = new FileInfo(OP.FileName);
if (File.Exists)
{
PathName = File.FullName;
}
}
if (PathName != String.Empty)
{
textBox1.Text = PathName;
listBox1.Items.Add(PathName);
}
}
private void cmdStart_Click(object sender, EventArgs e)
{
string SelectedItem = "";
if (listBox1.SelectedItem != null)
{
SelectedItem = listBox1.SelectedItem.ToString();
/*MessageBox.Show(SelectedItem);*/
}
Process Pro = new Process();
Pro.StartInfo.FileName = SelectedItem;
DialogResult Ergebnis2 = MessageBox.Show("Would you like to start the Game right now?", "Game start?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (Ergebnis2.Equals(true))
{
try
{
Pro.Start();
}
catch (Exception)
{
MessageBox.Show("The Start of the Program was aborted!\r\nOr you didn't specify the right Path!", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
private void cmdSave_Click(object sender, EventArgs e)
{
StreamWriter SaveFile = new StreamWriter(#"C:\Users\" + Environment.UserName.ToString() + #"\Desktop\savedgames.txt");
foreach (var item in listBox1.Items)
{
SaveFile.WriteLine(item.ToString());
}
SaveFile.Close();
MessageBox.Show("EZPZ");
}
private void cmdLoad_Click(object sender, EventArgs e)
{
StreamReader sr = new StreamReader(#"C:\Users\" + Environment.UserName.ToString() + #"\Desktop\savedgames.txt");
string line = string.Empty;
try
{
line = sr.ReadLine();
while (line != null)
{
this.listBox1.Items.Add(line);
line = sr.ReadLine();
}
sr.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
finally
{
sr.Close();
}
}
}
Hello Stackoverflow-Community,
So i've tried to be able to start the selected File(from the Listbox) by clicking the Start button.The items in the Listbox are loaded in from a .txt-File, But it seems that the path that i get (from the .txt-File) is not actually the same that was written inside.
For example: H:\Exe\556689600.exe is written inside the .txt-File but when i check while pausing the application the value of the SelectedItem is "H:(two backslashes)Exe(two backslashes)556689600.exe" so i'd like it to be H:\Exe\556689600.exe so it can be properly started.
EDIT: The main problem is that i can't start the .exe that i selected (via cmdStart) and i don't know why.
Please keep in mind that i'm (as you can see from the code) not very experienced in programming and that i'm not an native english speaker, so pardon me for any grammatical mistakes/logic mistakes made.
Thanks in advance,
Stephen
The problem is with:
DialogResult Ergebnis2 = MessageBox.Show("Would you like to start the Game right now?", "Game start?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (Ergebnis2.Equals(true))
DialogResult holds the Enum data 'DialogResult.Yes', so you need to compare it to that value, and not (true).
Edit:
I suggest practicing working with debug:
In this case, I plated a breakpoint on the 'cmdstart_Click' method and followed it step by step (Used F10)
I saw that we jump over the 'if' condition, and checked why.

Open a directory and process files/folders in background worker query

I have the following code, I'm trying to open a directory and process the files in it via the Background worker but I am having issues with it.
The error I have is (The name filePath does not exist in the current context), which I can understand because it's stored in another method? if someone could point out to me what is wrong with my code it would be appreciated. Folderbrowser doesn't work under the Background worker section.
private void btnFiles_Click(object sender, EventArgs e)
{
//btnFiles.Enabled = false;
btnSTOP.Enabled = true;
//Clear text fields
listBoxResults.Items.Clear();
listBoxPath.Items.Clear();
txtItemsFound.Text = String.Empty;
//Open folder browser for user to select the folder to scan
DialogResult result = folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
{
//Store selected folder path
string filePath = folderBrowserDialog1.SelectedPath;
}
//Start the async operation here
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
//Process the folder
try
{
foreach (string dir in Alphaleonis.Win32.Filesystem.Directory.EnumerateFiles(filePath, "*.*", SearchOption.AllDirectories, true))
{
//Populate List Box with all files found
this.Invoke(new Action(() => listUpdate2(dir)));
FileInfo fi = new FileInfo(dir);
if (fi.Length == 0)
{
//Populate List Box with all empty files found
this.Invoke(new Action(() => listUpdate1(dir + Environment.NewLine)));
}
}
}
//Catch exceptions
catch (Exception err)
{
// This code just writes out the message and continues to recurse.
log.Add(err.Message);
//throw;
}
finally
{
//add a count of the empty files here
txtItemsFound.Text = listBoxResults.Items.Count.ToString();
// Write out all the files that could not be processed.
foreach (string s in log)
{
this.Invoke(new Action(() => listUpdate1(s)));
}
log.Clear();
MessageBox.Show("Scanning Complete", "Done", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
//If cancel button was pressed while the execution is in progress
//Change the state from cancellation ---> cancelled
if (backgroundWorker1.CancellationPending)
{
e.Cancel = true;
//backgroundWorker1.ReportProgress(0);
return;
}
//}
//Report 100% completion on operation completed
backgroundWorker1.ReportProgress(100);
}
#DonBoitnott solution is the most general for data flow inside class. Specifically to BackgroundWorker there is another one exists
private void btnFiles_Click(object sender, EventArgs e)
{
...
// pass folder name
backgroundWorker1.RunWorkerAsync(folderBrowserDialog1.SelectedPath);
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// get passed folder name
string filePath = (string)e.Argument;
...
}
The variable "filePath" is being declared local to the btnFiles_Click method. In order for it to be used elsewhere, it must be declared global to the code page:
public class Form1
{
private String _filePath = null;
private void btnFiles_Click(object sender, EventArgs e)
{
//get your file and assign _filePath here...
_filePath = folderBrowserDialog1.SelectedPath;
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
//use _filePath here...
}
}

How can I check if the path entered by user is valid or not? [duplicate]

This question already has answers here:
Check whether a path is valid
(12 answers)
Closed 8 years ago.
I have found this code while I was busy searching for an answer!
private void btnOpenFile_Click(object sender, EventArgs e)
{
OpenFileDialog saveFileDialogBrowse = new OpenFileDialog();
saveFileDialogBrowse.Filter = "Pcap file|*.pcap";
saveFileDialogBrowse.Title = "Save an pcap File";
saveFileDialogBrowse.ShowDialog();
var pcapFile = saveFileDialogBrowse.FileName; //do whatever you like with the selected filename
if (pcapFile != "")
{
FileInfo fileInfo = new FileInfo(pcapFile);
txtFilePath.Text = fileInfo.FullName;
}
}
There is no easy way.
You can use File.Exists to check for file existence on the path, but a change can still happen before the execution of the next line. Your best option is to combine File.Exists with try-catch to catch any possible exceptions.
private void btnOpenFile_Click(object sender, EventArgs e)
{
OpenFileDialog saveFileDialogBrowse = new OpenFileDialog();
saveFileDialogBrowse.Filter = "Pcap file|*.pcap";
saveFileDialogBrowse.Title = "Save an pcap File";
saveFileDialogBrowse.ShowDialog();
var pcapFile = saveFileDialogBrowse.FileName; //do whatever you like with the selected filename
try
{
if (File.Exists(pcapFile))
{
FileInfo fileInfo = new FileInfo(pcapFile);
txtFilePath.Text = fileInfo.FullName;
}
}
catch (FileNotFoundException fileNotFoundException)
{
//Log and handle
}
catch (Exception ex)
{
//log and handle
}
}
You can use the File.Exists method:
string fullPath = #"c:\temp\test.txt";
bool fileExists = File.Exists(fullPath);
You can use the File.Exists method, which is documented here.

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