how to use a variable from other context in c# - c#

I just need to know on how to use variable from other blocks or context(or whatever they call it)...
I was trying to create an app installer for windows 10 using powershell but i'm just a beginner for c#...
I have 2 Buttons the browse and install, I declare the location of the file in the browse button's block and I was trying to use that variable in the install button's context.
But all I got is "The name "appFile" does not exist in the current context."
Here's my code:
private void button3_Click(object sender, EventArgs e)
{
MessageBox.Show("Created by Carlos Miguel Salamat","Windows App Installer");
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog file = new OpenFileDialog();
file.Title = "Choose Package File";
file.InitialDirectory = #"c:\";
file.Filter = "All files (*.*)|*.*|All files (*.*)|*.*";
file.FilterIndex = 2;
file.RestoreDirectory = true;
if (file.ShowDialog() == DialogResult.OK)
{
textBox1.Text = file.FileName;
string appFile = file.FileName;
}
}
private void button2_Click(object sender, EventArgs e)
{
string strCmdText;
strCmdText = "powershell.exe add-appxpackage";
System.Diagnostics.Process.Start("CMD.exe", strCmdText, appFile);
}
}
}
`

Define it to global,
string appFile = "";
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog file = new OpenFileDialog();
file.Title = "Choose Package File";
file.InitialDirectory = #"c:\";
file.Filter = "All files (*.*)|*.*|All files (*.*)|*.*";
file.FilterIndex = 2;
file.RestoreDirectory = true;
if (file.ShowDialog() == DialogResult.OK)
{
textBox1.Text = file.FileName;
this.appFile = file.FileName;
}
}
private void button2_Click(object sender, EventArgs e)
{
string strCmdText;
strCmdText = "powershell.exe add-appxpackage";
System.Diagnostics.Process.Start("CMD.exe", strCmdText, this.appFile);
}
Hope helps,

The answers are obviously correct, but before blindly applying them, I would strongly advice you to look for some 101 on programming and Object Orientation. Variable scoping rules are very similar among most languages. You will find yourself in similar puzzling situations if you try to skip the basics.

You need to put the variable at least in the class context to access it from other methods within this class. If you need to access it from outside the class you need to make it public and add setter/getter
public class YourClass {
public string AppFile {get;set;}
private void button3_Click(object sender, EventArgs e)
{
MessageBox.Show("Created by Carlos Miguel Salamat","Windows App Installer");
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog file = new OpenFileDialog();
file.Title = "Choose Package File";
file.InitialDirectory = #"c:\";
file.Filter = "All files (*.*)|*.*|All files (*.*)|*.*";
file.FilterIndex = 2;
file.RestoreDirectory = true;
if (file.ShowDialog() == DialogResult.OK)
{
textBox1.Text = file.FileName;
this.AppFile = file.FileName;
}
}
private void button2_Click(object sender, EventArgs e)
{
string strCmdText;
strCmdText = "powershell.exe add-appxpackage";
System.Diagnostics.Process.Start("CMD.exe", strCmdText, this.AppFile);
}
}
You could also use the Text Property from your textBox1 like this:
private void button2_Click(object sender, EventArgs e)
{
string strCmdText;
strCmdText = "powershell.exe add-appxpackage";
System.Diagnostics.Process.Start("CMD.exe", strCmdText, textBox1.Text);
}
But I would definetaly advice you to use the first solution.

You can read & learn about it here:
https://msdn.microsoft.com/en-us/library/ms973875.aspx
Might be a short answer but rather than giving you a fish you better learn how to catch it yourself.

Wim, is right. You would do well breaking that type of code up into say a class called file, then just call it on the click method. That way you can reference it from other methods in a different class. Just my opinion when working with complex Objects.

Related

File being used by another process when using File.CopyTo method

This is the code for my windows form. The goal of the form is to be able to preview a pdf on the application and then chose a folder with a drop down that you would like to copy the file to (this is what a "house" refers to in the code). This is a little project for work to make it simpler to organize files that get sent to the company. The listBox works populating with all the pdfs and the preview window works as well (this is the axAcroPDF component). But when hitting the send button to copy the file it says the file is being used by another process.
public partial class Form1 : Form { public Form1() { InitializeComponent();
}
string selectedPDF = "";
string selectedHouse = "";
DirectoryInfo currentPDF;
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "PDF Files(*.pdf) |*.pdf;";
openFileDialog1.ShowDialog();
if(openFileDialog1.FileName != null)
{
axAcroPDF1.LoadFile(openFileDialog1.FileName);
}
}
private void refreshBTN_Click(object sender, EventArgs e)
{
DirectoryInfo dinfo = new DirectoryInfo(#"C:\Users\bkamide\Desktop\ExamplePDFS");
FileInfo[] smFiles = dinfo.GetFiles("*.pdf");
foreach (FileInfo fi in smFiles)
{
pdfList.Items.Add(Path.GetFileName(fi.Name));
}
}
private void pdfList_SelectedIndexChanged(object sender, EventArgs e)
{
string firstSelectedItem = pdfList.SelectedItem.ToString();
selectedPDF = firstSelectedItem;
DirectoryInfo dinfo = new DirectoryInfo(#"C:\Users\bkamide\Desktop\ExamplePDFS\" + firstSelectedItem);
currentPDF = dinfo;
}
private void btnSend_Click(object sender, EventArgs e)
{
openFileDialog1.Reset();
axAcroPDF1.EndInit();
var sourceFile = new FileInfo(currentPDF.FullName);
var dest = Path.Combine(#"C:\Users\bkamide\Desktop\ExamplePDFS\", selectedHouse, sourceFile.FullName);
sourceFile.CopyTo(dest, true);
}
private void cbHouse_SelectedIndex(object sender, EventArgs e)
{
selectedHouse = cbHouse.SelectedIndex.ToString();
}
}
I tried in the send method to reset the openFileDialog and axAcroPDF (not sure if I did that right) to see if those were the processes that could be using the file. I also tried restarting my computer to make sure nothing in the background was using it as well. I also did try the using method but I was not quite sure how to implement it within this.

C# WinForms how to use a non-static string from one void to another?

As a small beginner-ish project i'm making a simple program that can play .wav files, I've encountered an issue however where in stuck in a situation where the program gets the file path and name from one void but I need to use that string in another void, example code here:
public void ChooseFile_Click(object sender, EventArgs e)
{
OpenFile.InitialDirectory = #"C:\";
OpenFile.RestoreDirectory = true;
OpenFile.FileName = "";
OpenFile.Title = "Open .wav file";
OpenFile.Filter = "wav files (*.wav)|*.wav";
OpenFile.ShowDialog();
string fileName = OpenFile.FileName;
ChosenFileText.Text = fileName;
}
public void PlayButton_Click(object sender, EventArgs e)
{
SoundPlayer sound = new SoundPlayer(fileName);
sound.Play();
}
As you can see I need to use the fileName string with the SoundPlayer but currently I get the error:
"The name 'fileName' does not exist in the current context".
I've tried making it public and static but all I get is errors, does anyone know how I can work around this?
You have to define the variable inside the class so that everyone can access it.
string fileName="";
public void ChooseFile_Click(object sender, EventArgs e)
{
OpenFile.InitialDirectory = #"C:\";
OpenFile.RestoreDirectory = true;
OpenFile.FileName = "";
OpenFile.Title = "Open .wav file";
OpenFile.Filter = "wav files (*.wav)|*.wav";
OpenFile.ShowDialog();
fileName = OpenFile.FileName;
ChosenFileText.Text = fileName;
}
public void PlayButton_Click(object sender, EventArgs e)
{
SoundPlayer sound = new SoundPlayer(fileName);
sound.Play();
}

Using Visual Studio and Windows Forms (C#) to upload and rename file to network drive

Here's some code I'm working on:
private void Form1_Load(object sender, EventArgs e)
{
}
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
{
OpenFileDialog openFileDialog1 = new OpenFileDialog
{
InitialDirectory = #"C:\",
Title = "Add a PDF",
CheckFileExists = true,
CheckPathExists = true,
DefaultExt = "pdf",
Filter = "pdf files (*.pdf)|*.pdf",
FilterIndex = 2,
RestoreDirectory = true,
ReadOnlyChecked = true,
ShowReadOnly = true
};
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = openFileDialog1.FileName;
string myFile = textBox1.Text;
Console.WriteLine(myFile);
}
}
}
private void button2_Click(object sender, EventArgs e)
{
System.IO.File.Move(myFile, #"C:\testing\records\file.pdf");
}
}
}
So anyway toward the bottom at button2, I'm trying to set up a few things. I want to add a button that saves the file using the System.IO line there. But when I add the button, I can't get it to work properly. The "myFile" variable doesn't seem to be declared anymore. I'm sure this is probably the messiest code anyone will paste on here today, but a lot of it was auto-genned by Visual Studio and I'm afraid to clean it up because I'm not 100% sure what some of this stuff is. I have tried cutting and pasting the button stuff up nearer to the myFile variable declaration since it's private and maybe that's why it doesn't know what it means anymore. But when I move it up there, I get a different error regarding the "private" at the beginning of the button call.
The issue here is that you're declaring your myFile variable within the scope of the if statement and so when that if statement block exits the myFile variable goes out of scope and no longer exists.
To get it to work you need to move the creation of the myFile variable to the class level.
public class Form1 : Form
{
private string myFile;
public Form1()
{
InitializeComponent();
}
// Other code snipped out
}
Now modify your button1_Click code so that instead of creating an instance of myFile:
string myFile = textBox1.Text;
You just populate the private variable you declared in the main part of the code:
myFile = textBox1.Text;
So the if statement looks like this:
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = openFileDialog1.FileName;
myFile = textBox1.Text;
Console.WriteLine(myFile);
}
You need a little modification to button2_Click:
private void button2_Click(object sender, EventArgs e)
{
// Check that myFile has some text and isn't null.
if (string.IsNullOrWhitespace(myFile))
return;
// Check that the file exists before attempting to move it.
if (File.Exists(myFile))
System.IO.File.Move(myFile, #"C:\testing\records\file.pdf");
}

Trying to save file without using SaveFileDialog

I am creating a text editor and i am stuck on the SaveFileDialog window opening
and asking to overwrite the current file open.
I have seen all the similar questions asked like this on SO but none have been able to help me. I have even tried the code from this question: "Saving file without dialog" Saving file without dialog
I got stuck on my program having a problem with FileName.
Here is the code i have currently
namespace Text_Editor
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
richTextBox1.Clear();
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
open.Title = "Open File";
open.FileName = "";
if (open.ShowDialog() == DialogResult.OK)
{
this.Text = string.Format("{0}", Path.GetFileNameWithoutExtension(open.FileName));
StreamReader reader = new StreamReader(open.FileName);
richTextBox1.Text = reader.ReadToEnd();
reader.Close();
}
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog save = new SaveFileDialog();
save.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
save.Title = "Save File";
save.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (save.ShowDialog() == DialogResult.OK)
{
StreamWriter writer = new StreamWriter(save.FileName);
writer.Write(richTextBox1.Text);
writer.Close();
}
}
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saving = new SaveFileDialog();
saving.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
saving.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
saving.Title = "Save As";
saving.FileName = "Untitled";
if (saving.ShowDialog() == DialogResult.OK)
{
StreamWriter writing = new StreamWriter(saving.FileName);
writing.Write(richTextBox1.Text);
writing.Close();
}
}
}
}
So my question is how can i modify my code so that i can save a file currently open without having the SaveFileDialog box opening everytime?
I do understand that it has something to do with the fact that i'm calling .ShowDialog but i don't know how to modify it.
When opening the file, save the FileName in a form-level variable or property.
Now while saving the file, you can use this FileName instead of getting it from a FileOpenDialog.
First declare a variable to hold filename at form level
// declare at form level
private string FileName = string.Empty;
When opening a file, save the FileName in this variable
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
open.Title = "Open File";
open.FileName = "";
if (open.ShowDialog() == DialogResult.OK)
{
// save the opened FileName in our variable
this.FileName = open.FileName;
this.Text = string.Format("{0}", Path.GetFileNameWithoutExtension(open.FileName));
StreamReader reader = new StreamReader(open.FileName);
richTextBox1.Text = reader.ReadToEnd();
reader.Close();
}
}
And when doing SaveAs operation, update this variable
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saving = new SaveFileDialog();
saving.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
saving.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
saving.Title = "Save As";
saving.FileName = "Untitled";
if (saving.ShowDialog() == DialogResult.OK)
{
// save the new FileName in our variable
this.FileName = saving.FileName;
StreamWriter writing = new StreamWriter(saving.FileName);
writing.Write(richTextBox1.Text);
writing.Close();
}
}
The save function can then be modified like this:
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(this.FileName))
{
// call SaveAs
saveAsToolStripMenuItem_Click(sender, e);
} else {
// we already have the filename. we overwrite that file.
StreamWriter writer = new StreamWriter(this.FileName);
writer.Write(richTextBox1.Text);
writer.Close();
}
}
In the New (and Close) function, you should clear this variable
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
// clear the FileName
this.FileName = string.Empty;
richTextBox1.Clear();
}
Create a new string variable in your class for example
string filename = string.empty
and then
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
if(string.IsNullOrEmpty(filename)) {
//Show Save filedialog
SaveFileDialog save = new SaveFileDialog();
save.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
save.Title = "Save File";
save.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (save.ShowDialog() == DialogResult.OK)
{
filename = save.FileName;
}
}
StreamWriter writer = new StreamWriter(filename);
writer.Write(richTextBox1.Text);
writer.Close();
}
The SaveFileDialog now only opens if fileName is null or empty
You will have to store the fact that you have already saved the file, e.g. by storing the file name in a member variable of the Form class you have. Then use an if to check whether you have already saved your file or not, and then either display the SaveFileDialog using ShowDialog() (in case you haven't) or don't and continue to save to the already defined file name (stored in your member variable).
Give it a try, do the following:
Define a string member variable, call it _fileName (private string _fileName; in your class)
In your saveToolStripMenuItem_Click method, check if it's null (if (null == _fileName))
If it is null, continue as before (show dialog), and after getting the file name, store it in your member variable
Refactor your file writing code so that you either get the file name from the file dialog (like before), or from your member variable _fileName
Have fun, C# is a great language to program in.
First, extract method from saveAsToolStripMenuItem_Click: what if you want add up a popup menu, speed button? Then just implement
public partial class Form1: Form {
// File name to save text to
private String m_FileName = "";
private Boolean SaveText(Boolean showDialog) {
// If file name is not assigned or dialog explictly required
if (String.IsNullOrEmpty(m_FileName) || showDialog) {
// Wrap IDisposable into using
using (SaveFileDialog dlg = new SaveFileDialog()) {
dlg.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
dlg.Title = "Save File";
dlg.FileName = m_FileName;
if (dlg.ShowDialog() != DialogResult.OK)
return false;
m_FileName = dlg.FileName;
}
}
File.WriteAllText(m_FileName, richTextBox1.Text);
this.Text = Path.GetFileNameWithoutExtension(m_FileName);
return true;
}
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e) {
// SaveAs: always show the dialog
SaveText(true);
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e) {
// Save: show the dialog when required only
SaveText(false);
}
...
}

If/Else with C#

Okay, so I'm working with some if/else statements now. But, I'm having some trouble.
Here's the full code that is depending on the version clicked.
private void button_Click(object sender, EventArgs e)
{
using (OpenFileDialog file = new OpenFileDialog())
{
file.Filter = "File(*.file)|*.jar|All Files (*.*)|*.*";
file.Title = "Open File...";
if (file.ShowDialog() == DialogResult.OK)
{
string fullFileName = item.FileName;
FileInfo userSelected = new FileInfo(fullFileName);
string fileNameWithExt = Path.GetFileName(fullFileName);
string destPath = Path.Combine(Application.UserAppDataPath, fileNameWithExt);
string mcAD = Environment.ExpandEnvironmentVariables("%AppData%");
File.Copy(item.FileName, mcAD, true);
}
}
But what I'm having trouble is with this.
Below is the code, but here's how the program is lain out.
There's a menu at the bottom of the program. It's named "Version" you click and you can choose version 1.0, 2.0, and 3.0. I have it set so there's text beside it telling it which version you chose.
Now, the issue is I need an if/else statement for all the version for the above code cause all files for each version go to a different location.
Here's the other code...
private void Version_1_0_Click(object sender, EventArgs e)
{
string Version_1_0_Selected = VersionText.Text = "1.0 Selected";
}
private void Version_1_6_1_Click(object sender, EventArgs e)
{
string Version_2_0_Selected = VersionText.Text = "2.0 Selected";
}
private void Version_3_0_Click(object sender, EventArgs e)
{
string Version_3_0_Selected = VersionText.Text = "3.0 Selected";
}
You can use Control.Tag for storing version index. For example:
private void Version_1_0_Click(object sender, EventArgs e)
{
VersionText.Text = "1.0 Selected";
VersionText.Tag= 1;
}
Then, you can define your target paths:
string[] paths = {#"c:\path1.txt", #"c:\path2.txt", #"c:\path3.txt"};
Finally, when you writing your files you can lookup the path like this:
File.Copy(item.FileName, paths[VersionText.Tag], true);
You might need to modify this code if the target file name is based on the source file name, but that should not be difficult.
Abstract the FileDialog code to a separate method and pass in your version string so that you can then perform the checks.
public void OpenVersionDialog(string version)
{
string mcAD = GetCopyPath(version);
if(!String.IsNullOrEmpty(mcAD))
{
using (OpenFileDialog file = new OpenFileDialog())
{
file.Filter = "File(*.file)|*.jar|All Files (*.*)|*.*";
file.Title = "Open File...";
if (file.ShowDialog() == DialogResult.OK)
{
string fullFileName = item.FileName;
FileInfo userSelected = new FileInfo(fullFileName);
string fileNameWithExt = Path.GetFileName(fullFileName);
string destPath = Path.Combine(Application.UserAppDataPath, fileNameWithExt);
File.Copy(item.FileName, mcAD, true);
}
}
}
else
{
//invalid version selected
}
}
public string GetCopyPath(string versionInput)
{
//these are case-insensitive checks but you can change that if you want case-sensitive
if(string.Equals(versionInput, "1.0 Selected", StringComparison.OrdinalIgnoreCase))
return "YOUR_PATH_FOR 1.0";
if(string.Equals(versionInput, "2.0 Selected", StringComparison.OrdinalIgnoreCase))
return "YOUR_PATH_FOR 2.0";
if(string.Equals(versionInput, "3.0 Selected", StringComparison.OrdinalIgnoreCase))
return "YOUR_PATH_FOR 3.0";
return String.Empty;
}
If I understand correctly that should be what you want. If you have more versions, you could store them in a dictionary where the key is the version and the value is the path that the file should be copied to.
I'm not sure what the difference between mcAD and destPath is but I assume mcAD is the variable that changes based on the version as that's being used in File.Copy.

Categories

Resources