If/Else with C# - 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.

Related

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();
}

how to use a variable from other context in 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.

I have a query about checked list boxes in c#

I have set up a program that so far can browse for the location of a file that possesses data in a text file holding the locations of other files which then shows me if they exist, are missing or are a duplicate inside listboxes. The next step is to enable the user to select files in the checked list boxes and being given the option to either move or copy. I have already made buttons which allow this but I want to be able to use them for the checked boxes I the list boxes.(p.s) please ignore any comments I have made in the code they are just previous attempts of doing other things in the code.
My code so far:
namespace File_existence
{
public partial class fileForm : Form
{
private string _filelistlocation;
public fileForm()
{
InitializeComponent();
}
private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
public void fileForm_Load(object sender, System.EventArgs e)
{
_filelistlocation = textBox1.Text;
}
private void button1_Click(object sender, System.EventArgs e)
{
//GetDuplicates();
checkedListBox1.Items.Clear();
listBox2.Items.Clear();
ReadFromList();
}
private void GetDuplicates()
{
DirectoryInfo directoryToCheck = new DirectoryInfo(#"C:\\temp");
FileInfo[] files = directoryToCheck.GetFiles("*.*", SearchOption.AllDirectories);
var duplicates = files.GroupBy(x => x.Name)
.Where(group => group.Count() > 1)
.Select(group => group.Key);
if (duplicates.Count() > 0)
{
MessageBox.Show("The file exists");
FileStream s2 = new FileStream(_filelistlocation, FileMode.Open, FileAccess.Read, FileShare.Read);
// open _filelistlocation
// foreach line in _filelistlocation
// concatenate pat hand filename
//
}
}
public void ReadFromList()
{
int lineCounter = 0;
int badlineCounter = 0;
using (StreamReader sr = new StreamReader(_filelistlocation))
{
String line;
while ((line = sr.ReadLine()) != null)
{
string[] values = line.Split('\t');
if (values.Length == 2)
{
string fullpath = string.Concat(values[1], "\\", values[0]);
if (File.Exists(fullpath))
checkedListBox1.Items.Add(fullpath);
else
listBox2.Items.Add(fullpath);
++lineCounter;
}
else
++badlineCounter;
//Console.WriteLine(line);
}
}
}
//StreamReader files= new StreamReader(File)();
private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
}
private void button2_Click(object sender, System.EventArgs e)
{
FolderBrowserDialog folderBrowserDlg = new FolderBrowserDialog();
folderBrowserDlg.ShowNewFolderButton = true;
DialogResult dlgResult = folderBrowserDlg.ShowDialog();
if (dlgResult.Equals(DialogResult.OK))
{
textBox1.Text = folderBrowserDlg.SelectedPath;
Environment.SpecialFolder rootFolder = folderBrowserDlg.RootFolder;
}
try
{
string fileName = "filetest1.txt";
string sourcePath = #"C:\Temp\Trade files\removed";
string targetPath = #"C:\Temp\Trade files\queued";
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath,fileName);
System.IO.File.Copy(sourceFile, destFile, true);
}
catch (IOException exc)
{
MessageBox.Show(exc.Message);
}
}
private void button3_Click(object sender, System.EventArgs e)
{
try
{
string sourceFile = #"C:\Temp\Trade Files\queued\filetest1.txt";
string destinationFile = #"C:\Temp\Trade Files\processed\filetest1.txt";
System.IO.File.Move(sourceFile, destinationFile);
}
catch(IOException ex){
MessageBox.Show(ex.Message);//"File not found"
}
}
private void button4_Click(object sender, System.EventArgs e)
{
OpenFileDialog fileBrowserDlg = new OpenFileDialog();
//folderBrowserDlg.ShowNewFolderButton = true;
//folderBrowserDlg.SelectedPath = _filelistlocation;
fileBrowserDlg.FileName = textBox1.Text;
DialogResult dlgResult = fileBrowserDlg.ShowDialog();
if (dlgResult.Equals(DialogResult.OK))
{
textBox1.Text = fileBrowserDlg.FileName;
File_existence.Properties.Settings.Default.Save();
// Environment.SpecialFolder rootFolder = folderBrowserDlg.RootFolder;
}
}
private void button5_Click(object sender, System.EventArgs e)
{
if (!textBox1.Text.Equals(String.Empty))
{
if (System.IO.Directory.GetFiles(textBox1.Text).Length > 0)
{
foreach (string file in System.IO.Directory.GetFiles(textBox1.Text))
{
checkedListBox1.Items.Add(file);
}
}
else
{
checkedListBox1.Items.Add(String.Format("No file found: {0}", textBox1.Text));
}
}
}
}
}
The task I need to do is that the files that appear in the checked list box need to usually be moved or copied to another directory. That is fine as I can already do that with what I have coded, but what it does is it will move or copy all of the files in the checked list box. What I want to do is enable the user to only be able to select which files they what to move or copy through checking the checked list box so that only those files will be moved or copied.
EDIT: Could it be checkedListBox.checked items?

how to find that whether the file exist or not using c#

private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog FldrBrowseDlg = new FolderBrowserDialog();
FldrBrowseDlg.ShowNewFolderButton = true;
DialogResult DigRslt = FldrBrowseDlg.ShowDialog();
if (DigRslt.Equals(DialogResult.OK))
{
textBox1.Text = FldrBrowseDlg.SelectedPath;
Environment.SpecialFolder rootfolder = FldrBrowseDlg.RootFolder;
}
}
private void button2_Click(object sender, EventArgs e)
{
DirectoryInfo dir = new DirectoryInfo(textBox1.Text);
FileInfo[] files = dir.GetFiles("*doc.zip", SearchOption.AllDirectories);
foreach (FileInfo fl in files)
{
string s1 = fl.ToString();
string name = s1.Substring(0, 28);
string kyrname = name + ".txt";
if (File.Exists(textBox1.Text+"*/"+kyrname))
{
label1.Text = "have kyrplus";
}
else
{
listBox1.Items.Add(name);
}
I want to search the file but it is not taking the the path that I am giving in File.Exixts() function what to do?
Thats probably because your path is not correct.
File.Exists(textBox1.Text+"*/"+kyrname)
You need to check what is the value in your textBox1.Text and then you can concatenate the value with "*/" and .txt. It doesnt look to me as a valid path.
EDIT:
You can try like this if you are looking for a file in all the subdirectory
var file = Directory.GetFiles(textBox1.Text, kyrname, SearchOption.AllDirectories)
.FirstOrDefault();
if (file == null)
{
// File does not exist
}

c# saving a text in a specific directory

Here is my code;
private void button1_Click(object sender, EventArgs e)
{
string newFile =textBox1.Text;
string temp = newFile.Replace("YNATEST.", "");
SaveFileDialog a1 = new SaveFileDialog();
a1.FileName = "";
a1.Filter = "Text Files(*txt)|*.txt";
a1.DefaultExt = "txt";
a1.ShowDialog();
StreamWriter yazmaislemi = new StreamWriter(a1.FileName);
yazmaislemi.WriteLine(temp);
yazmaislemi.Close();
}
it is saving the text on Desktop but i want to save it to the following path:
C:\Users\esra.ur\Desktop\projee1
use save file dialog, so you can save your text in your specific directory
using System;
using System.ComponentModel;
using System.IO;
using System.Windows.Forms;
namespace WindowsFormsApplication30
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// When user clicks button, show the dialog.
saveFileDialog1.ShowDialog();
}
private void saveFileDialog1_FileOk(object sender, CancelEventArgs e)
{
// Get file name.
string name = saveFileDialog1.FileName;
// Write to the file name selected.
// ... You can write the text from a TextBox instead of a string literal.
File.WriteAllText(name, "test");
}
}
}
this code snippets is from this link http://www.dotnetperls.com/savefiledialog
I hope it will help
1) Wrap your show dialog to check the result.
if(a1.ShowDialog() == DialogResult.OK)
2) The SaveFileDialog has a property for setting an initial path. This is for the directory which will be shown when the dialog is first open. For the desktop you want to use the Environment.GetFolderPath like so.
a1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
3) Try to separate concerns:
private string OutputFile {get;set;}
private void button1_Click(object sender, EventArgs e)
{
if(string.IsNullOrEmpty(this.OutputPath))
{
SaveFileDialog a1 = new SaveFileDialog();
a1.FileName = textBox1.Text;
a1.Filter = "Text Files(*txt)|*.txt";
a1.DefaultExt = "txt";
a1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
if(a1.ShowDialog() == DialogResult.OK)
{
this.OutputFile = ai.FileName
}
}
this.SaveFile(this.OutputFile);
}
private void SaveFile(string FileName)
{
string newFile = FileName;
string temp = newFile.Replace("YNATEST.", "");
using(StreamWriter yazmaislemi = new StreamWriter(temp))
{
yazmaislemi.WriteLine(temp);
yazmaislemi.Close();
}
}
The SaveFileDialog object has a property called InitialDirectory, which is a string you can specify, for example
SaveFileDialog a1 = new SaveFileDialog();
a1.InitialDirectory = #"C:\Users\esra.ur\Desktop\projee1";
If this directory doesn't exist, it will default back to documents. Be careful about writing a file even if the user tries to cancel. Hope this helps?
In response to your comment, it sounds like you want to hard code the destination file name. This is dangerous as you can get an exception if the directory doesn't exist, but you can use the following: (I'm not sure what you want to do with the file name)
'string newFile = textBox1.Text;
string temp = newFile.Replace("YNATEST.", "");
StreamWriter yazmaislemi = new StreamWriter(#"C:\Users\esra.ur\Desktop\projee1\" + temp + ".txt");
yazmaislemi.WriteLine(temp);
yazmaislemi.Close();
In this case you don't need the SaveFileDialog at all. I think this is what you're asking for, but it's dangerous to code in this way.

Categories

Resources