Code not executing correctly in windows forms app - c#

I'm trying to make a windows form application to do the same thing that I have a console application doing. The design is just a box with two labels (going to try to add a progress bar later on) but for some reason the code is not working correctly.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
string date = DateTime.Now.ToString("ddMMyy");
string Source = #"G:\Personal\A1";
string Destination = #"D:\_Lil USB Backup\" + "b";
if (System.IO.Directory.Exists(Source))
{
if (System.IO.Directory.Exists(Destination))
{
infoBox.Text = "Backup already exists for today. U rem";
}
else
{
System.IO.Directory.CreateDirectory(Destination);
}
try
{
CopyAllFiles(Source, Destination);
infoBox.Text = "Files backed up successfully.";
if (System.IO.Directory.Exists(#"D:\" + date + #"System Volume Information"))
{
Directory.Delete(#"D:\" + date + #"System Volume Information", true);
infoBox.Text = "Files backed up successfully.\n System Volume Information folder deleted.\n Backup successfull.";
}
else
{
infoBox.Text = "System Volume Information folder does not exist and therefore was not deleted.\n Backup successfull.";
}
}
catch (Exception ez)
{
infoBox.Text = "Umm, something didn't work. Oh maybe it was this? " + ez.Message;
}
}
else
{
infoBox.Text = "Source does not exist, try plugging the USB in dipshit.";
}
}
private static void CopyAllFiles(string Source, string Destination)
{
try
{
// Get the subdirectories for the specified directory.
DirectoryInfo dir = new DirectoryInfo(Source);
DirectoryInfo[] dirs = dir.GetDirectories();
if (!dir.Exists)
{
Label infoBoxErr = new Label();
infoBoxErr.Text = "Directory could not be found.";
}
// If the destination directory doesn't exist, create it.
if (!Directory.Exists(Destination))
{
Directory.CreateDirectory(Destination);
}
// Get the files in the directory and copy them to the new location.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(Destination, file.Name);
file.CopyTo(temppath, true);
}
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(Destination, subdir.Name);
CopyAllFiles(subdir.FullName, temppath);
}
}
catch (Exception ex)
{
Label infoBoxErr = new Label();
infoBoxErr.Text = "Oh. Something didn't work, sorry. Might have been this: " + ex.Message + " lol!";
}
}
private void progressBar1_Click(object sender, EventArgs e)
{
}
}
}
The problem is that it outputs the text in the labels as expected as if it was successful. Yet it does not create a new folder or copy any of the files. I have no idea why and it's not giving me any errors!

First of all you catch exception within CopyAllFiles method. And its code
catch (Exception ex)
{
Label infoBoxErr = new Label();
infoBoxErr.Text = "Oh. Something didn't work, sorry. Might have been this: " + ex.Message + " lol!";
}
doesn't do anything because it creates label infoBoxErr in memory and doesn't display it at all.
So, the following code
try
{
CopyAllFiles(Source, Destination);
infoBox.Text = "Files backed up successfully.";
if (System.IO.Directory.Exists(#"D:\" + date + #"System Volume Information"))
{
Directory.Delete(#"D:\" + date + #"System Volume Information", true);
infoBox.Text = "Files backed up successfully.\n System Volume Information folder deleted.\n Backup successfull.";
}
else
{
infoBox.Text = "System Volume Information folder does not exist and therefore was not deleted.\n Backup successfull.";
}
}
catch (Exception ez)
{
infoBox.Text = "Umm, something didn't work. Oh maybe it was this? " + ez.Message;
}
never reaches the catch block (because of inner catch in CopyAllFiles method) and just displays success text.
So I'd suggest you to remove that inner catch and see what happens.

Related

How do I make my progressbar show the progess of a directory being copied [duplicate]

This question already has answers here:
Visual feedback on long running task
(1 answer)
C# WinForm progress bar not progressively increasing
(3 answers)
Closed 3 years ago.
I have a piece of code wich copies a folder to another directory. I wanted to implement a progress bar so the user can see the progress of the files being copied. I've tried some things, but I just cant get it to work.
This is the code I thought would do what I said above, but the progress bar doesn't make any progress, why the folder is actually being copied.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace intChanger
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
string Dirr;
string Dirr2;
int no = 0;
int Count = 0;
int Count2 = 0;
private void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
if (no == 0)
{
no = 1;
Dirr = sourceDirName;
Dirr2 = destDirName;
Count = Directory.GetFiles(Dirr, "*.*", SearchOption.AllDirectories).Length;
Count = 100 / Count;
}
// Get the subdirectories for the specified directory.
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
DirectoryInfo[] dirs = dir.GetDirectories();
// If the destination directory doesn't exist, create it.
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
// Get the files in the directory and copy them to the new location.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(destDirName, file.Name);
file.CopyTo(temppath, false);
Count2 = Count2 + 1;
progressBar1.Value = Count2 * Count;
}
// If copying subdirectories, copy them and their contents to new location.
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
private void button1_Click(object sender, EventArgs e)
{
DirectoryCopy(#"C:\Users\Stefan\Downloads\Portable Python 2.7.15 Basic (x64)\Portable Python 2.7.15 x64", #"C:\Users\Stefan\Documents\Backuppers_Backups\Portable Python 2.7.15 x64", true);
MessageBox.Show("Done coppieng", "Done", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
I expect the Progress bar to go slowly up, but it doesn't: It stays at 0
However it does actually copy the files
You should put the copy process in a BackgroundWorker and refresh the progress bar from the _bgwCopyOperation_ProgressChanged event.
Because you are processing the copy operation in the GUI thread, you block controls from refreshing.
Try something like this. You still need to modify this a bit to pass the parameters to the _bgwCopyOperation_DoWork event.
private void _bgwCopyOperation_DoWork(object sender, DoWorkEventArgs e)
{
if (no == 0)
{
no = 1;
Dirr = sourceDirName;
Dirr2 = destDirName;
Count = Directory.GetFiles(Dirr, "*.*", SearchOption.AllDirectories).Length;
Count = 100 / Count;
}
// Get the subdirectories for the specified directory.
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
DirectoryInfo[] dirs = dir.GetDirectories();
// If the destination directory doesn't exist, create it.
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
// Get the files in the directory and copy them to the new location.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(destDirName, file.Name);
file.CopyTo(temppath, false);
Count2 = Count2 + 1;
//Update progressbar here
_bgwCopyOperation.ReportProgress(Count2 * Count);
}
// If copying subdirectories, copy them and their contents to new location.
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
private void _bgwCopyOperation_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
The BackgroundWorker is certainly the best approach, it will send all the heavy copy into a separate thread an not keep the GUI thread busy with simple copy.
...but if you are copying small folders, you could try using the Refresh function on the progress bar:
using System;
using System.Threading;
using System.Windows.Forms;
namespace ProgressBat
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
progressBar1.Value = 0;
for (int i = 0; i < 100; i++)
{
progressBar1.Value = i;
progressBar1.Refresh();
Thread.Sleep(50);
}
button1.Enabled = true;
}
}
}
That example will get the progress bar moving correctly.
And it is a one line fix to your code

FileSystemWatcher works 3-5 times before throwing exceptions - C#

File comes in over EDI as .today. I need to change it to .txt and move it to another folder. Everything works just fine for about 3-5 files, then starts throwing exceptions. I tried handling those, but that doesn't solve the problem. I'm also getting sporadic (filename cannot be null) exceptions as well. I just can't seem to figure this out.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Diagnostics;
using System.Threading;
using System.Windows.Forms;
using System.Security.Permissions;
namespace FileConverterService
{
class ConverterService
{
//Configure watcher & input
private FileSystemWatcher _watcher;
public bool Start()
{
_watcher = new FileSystemWatcher(#"C:\FTP_base\temp", "*.today");
_watcher.Created += new FileSystemEventHandler(FileCreated);
_watcher.IncludeSubdirectories = false;
_watcher.EnableRaisingEvents = true;
return true;
}
//Configure output creation and append file name to include .txt extension
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
private void FileCreated(object sender, FileSystemEventArgs e)
{
try
{
string dateTime = DateTime.Now.ToString("yyyyMMddHHmmssfff");
string content = File.ReadAllText(e.FullPath);
string upperContent = content.ToUpperInvariant();
var dir = Path.GetDirectoryName(e.FullPath);
var convertedFileName = Path.GetFileName(e.FullPath) + dateTime + ".txt";
var convertedPath = Path.Combine(dir, convertedFileName);
File.WriteAllText(convertedPath, upperContent);
}
catch (IOException f)
{
if (f is IOException)
{
MessageBox.Show("Exception Caught"); //was just testing
}
}
MoveConvert();
}
//Move converted file to EDI processing folder
public static void MoveConvert()
{
try {
string dateTime = DateTime.Now.ToString("yyyyMMddHHmmssfff");
string rootFolderPath = #"C:\FTP_base\temp\";
string moveTo = #"C:\FTP_base\INbound\inbound_" + dateTime + ".txt";
//string moveTo = #"F:\FTP_base\Office Depot\INbound\inbound_" + dateTime + ".txt";
string filesToMove = #"*.txt"; // Only move .txt
string myfile2 = System.IO.Directory.GetFiles(rootFolderPath, filesToMove).FirstOrDefault();
string fileToMove = myfile2;
//moving file
File.Move(fileToMove, moveTo);
MoveOriginal();
}
catch (IOException e)
{
if (e is IOException)
{
MessageBox.Show("File already exists."); //was just testing
}
}
}
public static void MoveOriginal()
{
try {
string dateTime = DateTime.Now.ToString("yyyyMMddHHmmssfff");
string rootFolderPath2 = #"C:\FTP_base\temp\";
string moveTo2 = #"C:\FTP_base\archive\archive_" + dateTime + ".archive";
//string moveTo2 = #"F:\Xcelerator_EDI\OfficeDepot\DataFiles\Inbound\Archive2\archive_" + dateTime + ".archive";
string filesToMove2 = #"*.today"; // Only move .today
string myfile = System.IO.Directory.GetFiles(rootFolderPath2, filesToMove2).FirstOrDefault();
//foreach (string file in fileList)
string fileToMove2 = myfile;
//moving file
File.Move(fileToMove2, moveTo2);
}
catch (IOException e)
{
if (e is IOException)
{
MessageBox.Show("IO Exception Occurred"); //was just testing
}
}
}
//Stop Service control
public bool Stop()
{
_watcher.Dispose();
return true;
}
}
}
Perhaps the files are still in use. The FileSystemWatcher event is raised when a file is created, but the creating process can still be writing to it. See here for a possible solution.

Auto find files, pass to connection string and read

Firstly, I would just like to add that I am an absolute beginner at C#, I'm doing my best to learn so I am sorry if this is a noob question, but I have hit a brick wall.
I am working on a program that when finished it will find .DBF files from a specified folder, read the file and insert into a mysql database. I am stuck pretty much at the first hurdle.
I am trying to make the program loop through each file it finds and read them.
I can't seem to be able to access the filename string from the GetFiles() Void.
Is there another way around passing the filename to the queryString rather than specifying it myself?
here is my code -
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.OleDb;
namespace WindowsApplication4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//OPEN PROGRAM
private void Form1_Load(object sender, EventArgs e)
{
this.richTextBox1.Text = "Waiting for commands...";
this.toolStripStatusLabel1.Text = "Waiting for commands...";
}
// FIND FILES BUTTON CLICK
private void button1_Click(object sender, EventArgs e)
{
this.richTextBox1.Text = "Looking for files...";
GetFiles();
}
// function to read files at source
private void GetFiles()
{
List<String> Myfiles = new List<string>();
string[] allFiles = System.IO.Directory
.GetFiles(#"C:\Users\74-des\Desktop\", "*.DBF");
if (allFiles.Length > 0)
{
try
{
foreach (string filename in allFiles)
{
this.richTextBox1.Text = string.Join(Environment.NewLine,allFiles);
string filenameWithoutPath = Path.GetFileName(filename);
}
}
catch (SystemException excpt)
{
this.richTextBox1.Text = excpt.Message;
}
}
}
private void ReadData()
{
this.toolStripStatusLabel1.Text = "Preparing To Read Data";
this.Refresh();
DirectoryInfo dir = new DirectoryInfo(#"C:\Users\74-des\Desktop\");
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + dir + ";Extended Properties=dBase IV";
string queryString = "SELECT * FROM " + "test4.DBF";
try
{
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand(queryString, connection);
connection.Open();
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
if (reader.IsDBNull(1))
{
this.richTextBox1.Text = "Null";
}
else
{
string DATE = reader.GetValue(0).ToString();
string TIME = reader.GetValue(1).ToString();
string CODE = reader.GetValue(2).ToString();
string item = reader.GetValue(3).ToString();
this.richTextBox1.Text = DATE + TIME + " " + CODE + " " + item;
this.Refresh();
}
}
reader.Close();
connection.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button2_Click(object sender, EventArgs e)
{
ReadData();
}
}
}
you can do the following
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.OleDb;
namespace WindowsApplication4
{
public partial class Form1 : Form
{
private string mDirectory; // this will hold the directory path you are working on
private string[] mFiles; // this will hold all files in the selected directory
public Form1()
{
InitializeComponent();
}
//OPEN PROGRAM
private void Form1_Load(object sender, EventArgs e)
{
this.richTextBox1.Text = "Waiting for commands...";
this.toolStripStatusLabel1.Text = "Waiting for commands...";
}
// FIND FILES BUTTON CLICK
private void button1_Click(object sender, EventArgs e)
{
this.richTextBox1.Text = "Looking for files...";
GetFiles();
}
// function to read files at source
private void GetFiles()
{
mDirectory = #"C:\Users\74-des\Desktop\"; // better to use OpenFolderDialog to choose the directory
mFiles = System.IO.Directory.GetFiles(mDirectory, "*.DBF");
if (mFiles.Length > 0)
{
try
{
foreach (string filename in mFiles)
{
this.richTextBox1.Text = string.Join(Environment.NewLine, mFiles);
string filenameWithoutPath = System.IO.Path.GetFileName(filename);
}
}
catch (SystemException excpt)
{
this.richTextBox1.Text = excpt.Message;
}
}
}
private void ReadData()
{
this.toolStripStatusLabel1.Text = "Preparing To Read Data";
this.Refresh();
string connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=dBase IV", mDirectory);
try
{
foreach (var file in mFiles)
{
string queryString = string.Format("SELECT * FROM " + "{0}.DBF", System.IO.Path.GetFileNameWithoutExtension(file));
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand(queryString, connection);
connection.Open();
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
if (reader.IsDBNull(1))
{
this.richTextBox1.Text = "Null";
}
else
{
string DATE = reader.GetValue(0).ToString();
string TIME = reader.GetValue(1).ToString();
string CODE = reader.GetValue(2).ToString();
string item = reader.GetValue(3).ToString();
this.richTextBox1.Text = DATE + TIME + " " + CODE + " " + item;
this.Refresh();
}
}
reader.Close();
connection.Close();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button2_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(mDirectory))
MessageBox.Show("You should Get Files first!");
else
ReadData();
}
}
}
hope it will help you

how do I copy a folder to a USB? C#

I'm working on a project that will automatically update my USB with some files from my computer.
The program works on start up and monitors for any USB or CD that is plugged into the computer. My program is to then copy some folders and its files to the USB. I am having trouble copying the folders into the USB and would appreciate some help, thanks.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// this section starts the timer so it can moniter when a USB or CD is inserted into
// the computer.
//==================================================================================
private void Form1_Load(object sender, EventArgs e)
{
timer1.Interval = 100;
timer1.Start();
WindowState = FormWindowState.Minimized;
//===================================================================================
}
private void timer1_Tick(object sender, EventArgs e)
{
// this section checks to see if there is a drive type of USB and CDs.
foreach(DriveInfo drive in DriveInfo.GetDrives())
{
if (drive.DriveType == DriveType.Removable)
{
// this part is supposed to copy a folder from the PC and paste it to the USB
//==============================================================================
//==============================================================================
}
if (drive.DriveType == DriveType.CDRom)
{
// same thing but for CDs.
//==============================================================================
//==============================================================================
}
}
}
// this section opens a folderbrowserdialog that the users can use to access their folders
//and put them into a listbox so when a USB or CD is inserted it will copy those files into
// the storage devices.
//==============================================================================
private void button1_Click(object sender, EventArgs e)
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
listBox1.Items.Add(folderBrowserDialog1.SelectedPath);
//==============================================================================
}
}
}
}
Here is how it can be done:
private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories();
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(destDirName, file.Name);
file.CopyTo(temppath, false);
}
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
Use File.Copy and use the USB drive letter for the destination. For example:
string sourceDir = #"c:\current";
string backupDir = #"f:\archives\2008";
try
{
string[] picList = Directory.GetFiles(sourceDir, "*.jpg");
string[] txtList = Directory.GetFiles(sourceDir, "*.txt");
// Copy picture files.
foreach (string f in picList)
{
// Remove path from the file name.
string fName = f.Substring(sourceDir.Length + 1);
// Use the Path.Combine method to safely append the file name to the path.
// Will overwrite if the destination file already exists.
File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName), true);
}
// Copy text files.
foreach (string f in txtList)
{
// Remove path from the file name.
string fName = f.Substring(sourceDir.Length + 1);
try
{
// Will not overwrite if the destination file already exists.
File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName));
}
// Catch exception if the file was already copied.
catch (IOException copyError)
{
Console.WriteLine(copyError.Message);
}
}
// Delete source files that were copied.
foreach (string f in txtList)
{
File.Delete(f);
}
foreach (string f in picList)
{
File.Delete(f);
}
}
catch (DirectoryNotFoundException dirNotFound)
{
Console.WriteLine(dirNotFound.Message);
}
please refer to MSDN:
http://msdn.microsoft.com/en-us/library/bb762914.aspx

Image renaming program in C#/.NET

I am working on a .NET program that is intended to iterate through a selected directory and allow the renaming of image files after displaying the images. I feel through my code that around 98% of the program is done, but I used a while loop to wait for the pressing of a button so as to allow for the renaming of the image file. Yet, the while loop freezes the program every time the while loop is iterated.
How can I either system("pause"); like in C++ to have the while loop pause without freezing the program and creating an infinite loop or how can I have the while loop paused automatically until a button is pressed?
Here is a tidbit of the code for the loop:
paused = true;
bool X = false;
label2.Text = "please choose a file name and press next";
//while statement
while (X == false)
{
if (paused == false)
{
//Renames filename
string newFileName = filenameTextbox.Text;
//Adds filename to selected directory where user wishes to send file to
string outputFile = destinationDirectory + "\\" + intCounter + fileNameOfficial;
//Pause statement to move to next operand..
//Copies post iterated file to selected directory
File.Copy(inputFile, outputFile, true);
X = true;
}
}
The code in its entirety is below.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Collections;
namespace recursionBitches
{
public partial class fileSorter : Form
{
bool paused = true;
public fileSorter()
{
InitializeComponent();
}
private void browseFrom_Click(object sender, EventArgs e)
{
//Warning dialouge for selecting a large file.
MessageBox.Show("Warning, before selecting the origination file, it is important to note that choosing too large of a directory (for example, my documents or 'C://') more than likely will cause this program to freeze. ");
MessageBox.Show("You have been warned");
//Choose the originating dir path. This dir path is to be later sorted using recursion.
//Once the originating dir path is chosen, it is added to the label above the button.
if (fromBrowse.ShowDialog(
) == DialogResult.OK)
{
this.originationLabel.Text = fromBrowse.SelectedPath;
}
}
private void browseTo_Click(object sender, EventArgs e)
{
//Choose the send to dir path. This dir path is to later have the files that are sorted sent to it.
//Once the to dir path is chosen, it is added to the label above the button.
if (toBrowse.ShowDialog(
) == DialogResult.OK)
{
this.sendingLabel.Text = toBrowse.SelectedPath;
}
}
private void sortButton_Click(object sender, EventArgs e)
{
string fileExtension = "*" + fileExtensionTextbox.Text;
//Check from path to ensure they are set to a user defined path.
int intCounter = 1;
if (originationLabel.Text != "From")
{
//Check to path to ensure it is set to a user defined path.
if (sendingLabel.Text != "To")
{
//Recursion stuff...
string sourceDirectory = fromBrowse.SelectedPath;
string destinationDirectory = toBrowse.SelectedPath;
//Sends origination path to function ae this is a function call. its num = 8675309... I think its name is Jenny.
recursiveRecursion(sourceDirectory, destinationDirectory, fileExtension, intCounter);
}
else
{
//Message box that says it is required to
MessageBox.Show("You dun goofed");
}
}
else
{
//Yup, it's a message box.
//That was an unhelpful comment....
/Aalmost as unhelpful as this comment
// This is what happens when I program stoned.
MessageBox.Show("You dun goofed");
}
//Grabs the path of the originating directory.
//After the originating directory path is choosen, send the path to a recursion function
//which will search the folders and sort the files in the dir. path.
}
private void originationLabel_Click(object sender, EventArgs e)
{
MessageBox.Show("Silly user, I am a label. I dont even click");
}
private void sendingLabel_Click(object sender, EventArgs e)
{
MessageBox.Show("Silly user, I am a label. I dont even click");
}
//Recursion function which grabs the directory path, uses a foreach loop to iterate through the files.
//Whilst each file is iterated through, have the recursive function select the files by extension and copy
//the files to another directory chosen by the user.
private void recursiveRecursion(string sourceDirectory, string destinationDirectory, string fileExtension, int intCounter)
{
//Select files Path and stuff
string[] filenames = Directory.GetFiles(sourceDirectory, fileExtension);
//foreach (string directoryName in directoryNames)
string[] directoryNames = Directory.GetDirectories(sourceDirectory);
//dir is the file name, as in for each file name in directory do the thing in this recursion loop thingy.
foreach (string fileName in filenames)
{
try
{
if (File.Exists(fileName))
{
//Don't use recursion. It is a file
//copy files here and stuff.
intCounter++;
//For the destination file ae dir2 to work, I need to get the file name from the file path.
//Currently dir is the file path.
//Enter code here to get the file name from the file path.
//Displays on label name of the file.
this.filesortTextbox.Text = "the file being copied is " + fileName;
//Gets filename from path
string fileNameOfficial = Path.GetFileName(fileName);
//Enters text of filename into filename textbox
filenameTextbox.Text = fileNameOfficial;
//For copying purposes, adds filename to originating directory path.
string inputFile = sourceDirectory + "\\" + fileNameOfficial;
//Assigns image from the origination directory.
Image img = Image.FromFile(inputFile);
// Shows image in the image viewer...
iteratedPicturebox.Image = img;
iteratedPicturebox.Width = img.Width;
iteratedPicturebox.Height = img.Height;
//Allows the user to change file name, after changing filename allows
//user to go to next file to rename. This is awesome for files...
paused = true;
bool X = false;
label2.Text = "Please choose a file name and press next.";
//while statement
while (X == false)
{
if (paused == false)
{
//Renames filename
string newFileName = filenameTextbox.Text;
//Adds filename to selected directory where user wishes to send file to.
string outputFile = destinationDirectory + "\\" + intCounter + fileNameOfficial;
//Pause statement to move to next operand..
//Copies post iterated file to selected directory.
File.Copy(inputFile, outputFile, true);
X = true;
}
}
}
else
{
//This really has an unknown pourpose, admittably keeping here for good luck...
Console.WriteLine("{0} is not a valid file or directory.", fileName);
}
}
catch (Exception e)
{
//What process failed you ask? Good question mate.
Console.WriteLine("The process failed: {0}", e.ToString());
}
}
//Long story short for each directory contained in the list of directories.
//Do the stuff listed in the foreach statement.
foreach (string directoryName in directoryNames)
{
try
{
if (Directory.Exists(directoryName))
{
//If this is a directory, send the thing through itself.
// MessageBox.Show("now going through the "+ directoryName + " directory");
recursiveRecursion(directoryName, destinationDirectory, fileExtension, intCounter);
this.directoryIterated.Text = "The Current Directory The Files Are being copied from is " + directoryName;
}
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
}
}
private void fileExtensionTextbox_TextChanged(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void directoryIterated_Click(object sender, EventArgs e)
{
MessageBox.Show("I am a label. I don't even click");
this.directoryIterated.Text = "You pressed me.";
}
private void kill_Click(object sender, EventArgs e)
{
Close();
}
private void filesortTextbox_Click(object sender, EventArgs e)
{
MessageBox.Show("I am a label. I don't even click.");
this.directoryIterated.Text = "You pressed me.";
}
private void iteratedPicturebox_Click(object sender, EventArgs e)
{
MessageBox.Show("I am a picture box, I don't even click.");
}
private void nextButton_Click(object sender, EventArgs e)
{
if (paused == false)
{
paused = true;
}
else
{
paused = false;
}
}
}
}
Consider using a BackgroundWorker for your processing loop. This allows you to process this on the background thread and won't freeze your main UI thread (which is what is happening)
Rather than trying to stop execution, I would display a dialog box:
Create form eg: FileRenameDialog.
Add public properties to form you can use to set From: text, etc.
Create instance of form. eg: FileRenameDialog reuseme
Whenever the user needs to make a selection, populate the text in the dialog. eg: reuseme.Source = "The current file being copied...";
Display the dialog to the user as modal eg: var dlgResult = reuseme.ShowDialog(this);
Do what you need to with the result eg: if (dlgResult == DialogResult.OK) {...do stuff with the properties of reuseme...}

Categories

Resources