How to save and load to preferences Windows Forms - c#

I am making program, which copy files from directory to other directories in Windows Forms C#. But I tried save and load directory path to Preferences > Settings and its not working. Copying, deleting its already good, only this saving and loading doesnt work. I want do this: user can in textbox write path to source and target directory and save it. That when user want copy files, he dont need write path again and again because program save path in this preferences.
Form:
There are source path and target path for directory. Then "Save values" should save this paths as string. And "Save backup" copy files. Text_box1 is textbox next to "Source path" and text_box2 is "Target path"
Here is code:
namespace AutoSave
{
public partial class Form1 : Form
{
string sourcePath;
string targetPath;
public Form1()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
var dir = new DirectoryInfo(targetPath);
if (dir.Exists)
{
DeleteDirectory(targetPath);
CopyFiles();
}
else
{
CopyFiles();
}
}
private void CopyFiles()
{
try
{
System.IO.Directory.CreateDirectory(targetPath);
var dir1 = new DirectoryInfo(sourcePath);
foreach (FileInfo file in dir1.GetFiles())
{
string targetFilePath = Path.Combine(targetPath, file.Name);
file.CopyTo(targetFilePath);
}
label2.Text = "Save is successful";
}
catch
{
label2.Text = "Something is wrong";
}
}
public static void DeleteDirectory(string target_dir)
{
string[] files = Directory.GetFiles(target_dir);
string[] dirs = Directory.GetDirectories(target_dir);
foreach (string file in files)
{
File.SetAttributes(file, FileAttributes.Normal);
File.Delete(file);
}
foreach (string dir in dirs)
{
DeleteDirectory(dir);
}
Directory.Delete(target_dir, false);
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
//SAVE PATHS
private void button2_Click(object sender, EventArgs e)
{
sourcePath = textBox1.Text;
targetPath = textBox2.Text;
Properties.Settings.Default.SourcePath = targetPath;
Properties.Settings.Default.TargetPath = sourcePath;
Properties.Settings.Default.Save();
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
}
Have I bad code or what I did bad please? Have you some tips? In advance I am sorry for my English i tried my best :D Thanks for help.

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.

Stuck with WMP in C#

I want to fetch 5 media files from a Directory [not with dialog box] and play with axwindowsmediaplayer in C# one after one. Songs to be played as playlist.
I am new to C#.
private void Form1_Load(object sender, EventArgs e)
{
/*
foreach(string dir in Directory.GetDirectories(#"E:\\Project"))
{
DirectoryInfo info = new DirectoryInfo(dir);
this.listBox1.Items.Add(info.Name);
}
foreach(string file in Directory.GetFiles("E:\\Project\\Surprise"))
{
FileInfo FileInfo = new FileInfo(file);
this.listBox1.Items.Add(FileInfo.Name);
}
*/
string path = #"E:\\Project\\Surprise";
foreach (string s in Directory.GetFiles(path, "*.mp4").Select(Path.GetFileName))
listBox1.Items.Add(s);
listBox1.SelectedItems.Clear();
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
axWindowsMediaPlayer1.URL = listBox1.SelectedItem.ToString();
axWindowsMediaPlayer1.Ctlcontrols.play();
}

open pdf file selected in listbox

I have all the dirctories (2014, 2012), the files of each selected folder (.pdf) in the listbox 2
I get the dirctories by this code
if (FBD.ShowDialog() == DialogResult.OK)
{
listBox1.Items.Clear();
DirectoryInfo[] diri_info = newDirectoryInfo(FBD.SelectedPath).GetDirectories();
foreach (DirectoryInfo diri in diri_info)
{
listBox1.Items.Add(diri);
}
and i get the files by this code
private void button1_Click(object sender, EventArgs e)
{
if (listBox1.SelectedIndex >= 0)
{
DirectoryInfo dirictory_choisis = (DirectoryInfo)listBox1.SelectedItem;
FileInfo[] files = dirictory_choisis.GetFiles();
listBox2.Items.Clear();
foreach (FileInfo file in files)
{
listBox2.Items.Add(file);
}
}
else
{
MessageBox.Show("selectioner un dossier");
}
}
Now how I can open the selected file (.pdf) ?
i use this code but dosn't work ( throw an exception file dosn't found)
private void listBox2_Click(object sender, EventArgs e)
{
FileInfo file = (FileInfo) listBox2.SelectedItem;
Process.Start(file.Name);
}
There is a syntax error in your code: "newDirectoryInfo"
By the way, file.Name only returns the name (not including path). You should replace that line with:
Process.Start(file.FullName);
So the listBox2_Click should be like this:
private void listBox2_Click(object sender, EventArgs e)
{
FileInfo file = (FileInfo)listBox2.SelectedItem;
Process.Start(file.FullName);
}

Using a ComboBox selection as directory source for another ComboBox, C#

So I have created a form that creates both a .txt file and a directory with the same name under the directory C:\Modules.
I have made it possible to select the .txt files from ModuleSelectorComboBox and now what I am having trouble getting to work is using the name of the file selected in ModuleSelectorComboBox to form part of the name of the directory in NoteSelectorComboBox.
public Default()
{
InitializeComponent();
System.IO.Directory.CreateDirectory(#"C:\Modules");
string[] files = Directory.GetFiles(#"C:\Modules");
foreach (string file in files)
ModuleSelectorComboBox.Items.Add(Path.GetFileNameWithoutExtension(file));
}
private void moduleToolStripMenuItem_Click(object sender, EventArgs e)
{
NewModule newmodule = new NewModule();
newmodule.Show();
}
private void ModuleSelectorComboBox_SelectedValueChanged(object sender, EventArgs e)
{
richTextBox1.Clear(); //Clears previous Modules Text
string ModulefileName = (string)ModuleSelectorComboBox.SelectedItem;
string filePath = Path.Combine(#"C:\Modules\", ModulefileName + ".txt");
if (File.Exists(filePath))
richTextBox1.AppendText(File.ReadAllText(filePath));
else
MessageBox.Show("There's been a problem. Please restart the program. \nError 1", "Error 1", //error 1 is file deleted while the program is running
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation,
MessageBoxDefaultButton.Button1);
}
private void button1_Click(object sender, EventArgs e)
{
ModuleSelectorComboBox.Items.Clear();
string[] files = Directory.GetFiles(#"C:\Modules");
foreach (string file in files)
ModuleSelectorComboBox.Items.Add(Path.GetFileNameWithoutExtension(file));
}
private void NoteSelectorComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
string ModulefileName = (string)ModuleSelectorComboBox.SelectedItem;
string[] files = Directory.GetFiles(#"C:\Modules\" + ModulefileName); //THIS IS WHAT I HAVE TRIED BUT CANNOT GET TO WORK
foreach (string file in files)
NoteSelectorComboBox.Items.Add(Path.GetFileNameWithoutExtension(file));
}
}
So if 'Module 1' is selected in the ModuleSelectorComboBox the directory listing for NoteSelectorComboBox will be set to C:\Modules\Module 1 (ie. C:\Modules\<NAME OF SELECTED MODULE From ModuleSelectorComboBox> and so the files in that folder would be shown in the ComboBox.
I have created an OnClick(); event that has now solved this issue.
private void button2_Click(object sender, EventArgs e)
{
string fileName = (string)ModuleSelectorComboBox.SelectedItem;
NoteSelectorComboBox.Items.Clear();
string[] files = Directory.GetFiles(#"C:\Modules\" + (string)ModuleSelectorComboBox.SelectedItem);
foreach (string file in files)
NoteSelectorComboBox.Items.Add(Path.GetFileNameWithoutExtension(file));
}

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?

Categories

Resources