I am currently working on my own MP3 player and want to add drag & drop functionality to be able to drag & drop your music either a file at a time or a whole directory at a time. I have the View of my ListView set to details, and am using the following code:
void Playlist_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
e.Effect = DragDropEffects.Copy;
}
void Playlist_DragDrop(object sender, DragEventArgs e)
{
Playlist.Items.Clear();
string[] songs = (string[])e.Data.GetData(DataFormats.FileDrop, false);
Parallel.ForEach(songs, s =>
{
if (File.Exists(s))
{
if (string.Compare(Path.GetExtension(s), ".mp3", true) == 0)
{
MessageBox.Show(s);
AddFileToListview(s);
}
}
else if (Directory.Exists(s))
{
DirectoryInfo di = new DirectoryInfo(s);
FileInfo[] files = di.GetFiles("*.mp3");
foreach (FileInfo file in files)
{
AddFileToListview(file.FullName);
MessageBox.Show(file.FullName);
}
}
});
}
private void AddFileToListview(string fullFilePath)
{
if (!File.Exists(fullFilePath))
return;
string song = Path.GetFileName(fullFilePath);
string directory = Path.GetDirectoryName(fullFilePath);
if (directory.EndsWith(Convert.ToString(Path.DirectorySeparatorChar)))
directory = directory.Substring(0, directory.Length - 1); //hack off the trailing \
ListViewItem itm = Playlist.Items.Add(song);
itm.SubItems.Add(directory); //second column = path
}
I have the MessageBox in there to make sure my code is being hit and tit always shows me the right data but nothing shows in the ListView. Any ideas what I'm doing wrong?
#ClearLogic: You were right I forgot to define columns in the ListView, thanks. Now I have another problem, I can drag multiple directories into the ListView with no problems, but when I try to add multiple single MP3's I get a cross-thread exception on the line
ListViewItem itm = Playlist.Items.Add(song);
Thanks to #ClearLogic for all their help in solving this issue, I thought I'd share my code in case someone else is having some issues as well.
private void Playlist_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
e.Effect = DragDropEffects.Copy;
}
private void Playlist_DragDrop(object sender, DragEventArgs e)
{
//get the file names
string[] songs = (string[])e.Data.GetData(DataFormats.FileDrop, false);
//we're using a Parallel.ForEach loop because if a directory is selected it can contain n number of items, this is to help prevent a bottleneck.
Parallel.ForEach(songs, song =>
{
//make sure the file exists
if (File.Exists(song))
{
//if it's an mp3 file then call AddFileToListview
if (string.Compare(Path.GetExtension(song), ".mp3", true) == 0)
{
AddFileToListview(song);
}
}
//A HA! It's a directory not a single file
else if (Directory.Exists(song))
{
//get the directory information
DirectoryInfo di = new DirectoryInfo(song);
//get all the mp3 files (will add WMA in the future)
FileInfo[] files = di.GetFiles("*.mp3");
//here we use a parallel loop to loop through every mp3 in the
//directory provided
Parallel.ForEach(files, file =>
{
AddFileToListview(file.FullName);
});
}
});
}
private void AddFileToListview(string fullFilePath)
{
double nanoseconds;
string totalTime = string.Empty;
//First things first, does the file even exist, if not then exit
if (!File.Exists(fullFilePath))
return;
//get the song name
string song = Path.GetFileName(fullFilePath);
//get the directory
string directory = Path.GetDirectoryName(fullFilePath);
//hack off the trailing \
if (directory.EndsWith(Convert.ToString(Path.DirectorySeparatorChar)))
directory = directory.Substring(0, directory.Length - 1);
//now we use the WindowsAPICodePack.Shell to start calculating the songs time
ShellFile shell = ShellFile.FromFilePath(fullFilePath);
//get the length is nanoseconds
double.TryParse(shell.Properties.System.Media.Duration.Value.ToString(), out nanoseconds);
//first make sure we have a value greater than zero
if (nanoseconds > 0)
{
// double milliseconds = nanoseconds * 0.000001;
TimeSpan time = TimeSpan.FromSeconds(Utilities.ConvertToMilliseconds(nanoseconds) / 1000);
totalTime = time.ToString(#"m\:ss");
}
//build oour song data
ListViewItem item = new ListViewItem();
item.Text = song;
item.SubItems.Add(totalTime);
//now my first run at this gave me a cross-thread exception when trying to add multiple single mp3's
//but I could add all the whole directories I wanted, o that is why we are now using BeginINvoke to access the ListView
if (Playlist.InvokeRequired)
Playlist.BeginInvoke(new MethodInvoker(() => Playlist.Items.Add(item)));
else
Playlist.Items.Add(item);
}
This code uses the WindowsAPICodePack to calculate the time of each song.
Related
I am a beginner at C# and I am writing a project where I created a method for reading a txt file.
I have a a textbox with a search button. What the program must do is read the input in the textbox, search in the file method and present the matching result in a list box.
I already have some coding like this, but it returns nothing. Can anyone help me?
private void searchButton_Click(object sender, EventArgs e)
{
String[] findValues = this.nameTextBox.Text.Split(new String[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
string newline = string.Empty;
gameListBox.Items.Clear();
ReadIntoArray();
string[][] games = new string[16][];
var index = BinSrchByName(nameTextBox.Text);
if (index != -1)
{
gameListBox.Items.Add(names[index] + " ==> $" + sales[index]);
}
else
{
MessageBox.Show("Data not found");
}
Please try the following (I wrote some comments to help you understand my method):
// Declare a list to hold the file lines
List<string> FileLines = new List<string>();
private void button_BrowseFile_Click(object sender, EventArgs e)
{
// Open a file dialog
using (OpenFileDialog openDialog = new OpenFileDialog())
{
// Set the file dialog to show only *.txt file or all files
openDialog.Filter = "Text files (*.txt)|*.txt|All Files (*.*)|*.*";
// Allow only single file selection
openDialog.Multiselect = false;
// Make sure the user didn't clicked the 'Cancel' button
if (openDialog.ShowDialog(this) == DialogResult.OK)
{
// Update the current file label with the filename only (not the full path)
label_CurrentFile.Text = $"Current file: {Path.GetFileName(openDialog.FileName)}";
// Add each line of the txt file into the list
foreach (string line in File.ReadAllLines(openDialog.FileName, Encoding.UTF8))
FileLines.Add(line);
}
}
}
private void button_DoSearch_Click(object sender, EventArgs e)
{
// Clear the list
list_SearchResults.Items.Clear();
// Count the number of line so you will be able to present it on the results list later on
int iLineNumber = 1;
// For each item in the 'FileLines' list
foreach (var item in FileLines)
{
// Check whether the current line contains the term the user typed in the searchbox
// I'm using 'ToLower()' to ignore case
if (item.ToLower().Contains(text_SearchTerm.Text.ToLower()))
{
// Create new ListViewItem to be added later on to the results list
// Add the first column the complete line that contains the term in the searchbox
ListViewItem lvi = new ListViewItem(item);
// Add the line number to the second column
lvi.SubItems.Add(iLineNumber.ToString());
// Add the ListviewItem to the results list
list_SearchResults.Items.Add(lvi);
}
// Increment the line number variable
iLineNumber++;
}
}
Screenshots:
Hope it helps!
This function receives the file path and the searched word and runs through the entire text file and returns the line where the requested word was found.
private string SearchText(string archivetxt, string word) {
StreamReader sr = new StreamReader(archivetxt);
while (!sr.EndOfStream) {
string s = sr.ReadLine();
if (s.IndexOf(word) > -1)
return s;
}
sr.Close();
return word + " not found";
}
Good day!
I'm trying to create a C # Forms app where user chooses directories with FolderDialog and paths are saved in list.txt file after read by textBox1.
In list.txt user can add and delete path.
code snippet:
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Lines = System.IO.File.ReadAllLines(fileName);
}
string fileName = Environment.CurrentDirectory + #"/etc/list.txt";
private void LoadTextboxes()
{
string[] loadedLines = System.IO.File.ReadAllLines(Environment.CurrentDirectory + #"/etc/list.txt");
int index = 0;
int n = int.Parse(loadedLines[index]);
string[] lines = new string[n];
Array.Copy(loadedLines, index + 1, lines, 0, n);
textBox1.Lines = lines;
}
private void DeleteFilesFromDirectory(string directoryPath)
{
DirectoryInfo d = new DirectoryInfo(directoryPath);
foreach (FileInfo fi in d.GetFiles())
{
fi.Delete();
}
foreach (DirectoryInfo di in d.GetDirectories())
{
DeleteFilesFromDirectory(di.FullName);
di.Delete();
}
}
private void button1_Del(object sender, EventArgs e)
{
DeleteFilesFromDirectory(textBox1.Text);
}
list.txt format:
C:/downloads
F:/doc/scan
D:/etc
t is important to delete only the sub folders and files but root folders must remain.
So far I have been done with my weak knowledge of c# and and now I'm stuck for a long time.
DeleteFilesFromDirectory only deletes the first line of textBox1.
How to make DeleteFilesFromDirectory read and delete all lines from textBox1?
Check this I tested it.
//put all paths in array reading line by line
string[] paths = System.IO.File.ReadAllLines(#"path-to\list.txt");
//get line by line paths
foreach (string path in paths)
{
if (Directory.Exists(path))
{
//deletes all files and parent
//recursive:true, deletes subfolders and files
Directory.Delete(path, true);
//create parent folder
Directory.CreateDirectory(path);
}
}//end outer for
Application I'm making give user ability to drag picture onto it and then copy this image to several folders at once.
Everything works great when I use local file, but I can't make it work with images dragged from internet browser directly on form.
Sure, image is saved in correct folders but name is changed to gibberish with .bmp extension.
So for example when I drag 100kb image with name "image.jpg" from browser I get 3mb image with name "sInFeER.bmp". I'm testing it on Firefox. I know I'm actually copying image from browser temp folder when I do that and file name is already changed there.
How can I keep correct file name and extension in this situation? (and preferably get image NOT converted to huge bmp file...)
Code I'm using for testing:
private void button10_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop, false) == true)
{
e.Effect = DragDropEffects.All;
}
}
private void button10_DragDrop(object sender, DragEventArgs e)
{
string[] draggedFiles = (string[])e.Data.GetData(DataFormats.FileDrop, false);
CatchFile(0, draggedFiles);
}
private void CatchFile(int id, string[] draggedFiles)
{
string directory = #”C:\test\”;
foreach (string file in draggedFiles)
{
Directory.CreateDirectory(directory);
File.Copy(file, directory + Path.GetFileName(file));
MessageBox.Show(Path.GetFileName(file)); // test
}
}
Thanks for all answers.
I've done some reading and decided that accessing original image when dragging from browser (Firefox) is pretty much impossible (without use of Firefox API), so I just used WebClient.DownloadFile to download dropped picture.
Here is code I ended with:
private void button10_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop, false) == true)
{
e.Effect = DragDropEffects.All;
}
}
private void button10_DragDrop(object sender, DragEventArgs e)
{
string draggedFileUrl = (string)e.Data.GetData(DataFormats.Html, false);
string[] draggedFiles = (string[])e.Data.GetData(DataFormats.FileDrop, false);
CatchFile(draggedFiles, draggedFileUrl);
}
private void CatchFile(string[] draggedFiles, string draggedFileUrl)
{
string directory = #"C:\test\";
foreach (string file in draggedFiles)
{
Directory.CreateDirectory(directory);
if (string.IsNullOrEmpty(draggedFileUrl))
{
if (!File.Exists(directory + Path.GetFileName(file))) File.Copy(file, directory + Path.GetFileName(file));
else
{
MessageBox.Show("File with that name already exists!");
}
}
else
{
string fileUrl = GetSourceImage(draggedFileUrl);
if (!File.Exists(directory + Path.GetFileName(fileUrl)))
{
using (var client = new WebClient())
{
client.DownloadFileAsync(new Uri(fileUrl), directory + Path.GetFileName(fileUrl));
}
}
else
{
MessageBox.Show("File with that name already exists!");
}
}
// Test check:
if (string.IsNullOrEmpty(draggedFileUrl)) MessageBox.Show("File dragged from hard drive.\n\nName:\n" + Path.GetFileName(file));
else MessageBox.Show("File dragged frow browser.\n\nName:\n" + Path.GetFileName(GetSourceImage(draggedFileUrl)));
}
}
private string GetSourceImage(string str)
{
string finalString = string.Empty;
string firstString = "src=\"";
string lastString = "\"";
int startPos = str.IndexOf(firstString) + firstString.Length;
string modifiedString = str.Substring(startPos, str.Length - startPos);
int endPos = modifiedString.IndexOf(lastString);
finalString = modifiedString.Substring(0, endPos);
return finalString;
}
There is probably better way of doing that but this works for me. Doesn't seem to work with other browsers. (but I needed it only to work with Firefox so I don't care)
Looks like you were dragging pixels from firefox to your app, not the url. I would look on the mozilla site for more info on how to drag the url to your app. They have lots of programming stuff and APIs to interact with the browser.
I have the following code, it finds and displays empty folders, unfortunately it can't handle all folders, The Recycle bin and the App data folder cause access exceptions.
Further down is an example from another user that uses enumeration, with it I can access restricted folders but it can't handle long paths.
I'm trying the Delimon.Win32.IO; namespace from http://gallery.technet.microsoft.com/scriptcenter/DelimonWin32IO-Library-V40-7ff6b16c It can apparently handle long paths (I've not tested it yet)
I need a solution that can handle access restrictions and long paths - if possible.
private void button1_Click(object sender, EventArgs e)
{
//Open folder browser for user to select the folder to scan
DialogResult result = folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
{
//Clear text fields
listBoxResults.Items.Clear();
listBoxPath.Items.Clear();
txtFoldersFound.Clear();
//Store selected folder path
string dirPath = folderBrowserDialog1.SelectedPath;
//Process the folder
try
{
foreach (string dir in Directory.GetDirectories(dirPath, "*.*", SearchOption.AllDirectories))
{
//Populate List Box with all folders found
this.Invoke(new Action(() => listUpdate2(dir)));
if (Directory.GetDirectories(dir).Length.Equals(0))
{
//Populate List Box with all empty folders found
this.Invoke(new Action(() => listUpdate1(dir + Environment.NewLine)));
}
}
//Count of the empty folders
txtFoldersFound.Text = listBoxResults.Items.Count.ToString();
}
//Catch exceptions, seems to be folders not accessible causing this. Recycle Bin, App Data etc
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
}
It seems that enumerating directories is still a problem in .NET 4.5:
https://connect.microsoft.com/VisualStudio/feedback/details/512171/directory-enumeratedirectory-etc-unusable-due-to-frequent-unauthorizedaccessexceptions-even-runas-administrator
The supplied code uses recursion to traverse the directory structure.
private void button1_Click(object sender, EventArgs e)
{
//Open folder browser for user to select the folder to scan
DialogResult result = folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
{
//Clear text fields
listBoxResults.Items.Clear();
listBoxPath.Items.Clear();
txtFoldersFound.Clear();
//Store selected folder path
string dirPath = folderBrowserDialog1.SelectedPath;
Action<string> performOnEachFolder = (s) => this.Invoke(new Action(() => listUpdate2(s)));
foreach (string emptyFolder in GetAllEmptyFolders(dirPath, performOnEachFolder))
this.Invoke(new Action(() => listUpdate2(emptyFolder)));
}
}
private static IEnumerable<string> GetAllEmptyFolders(string path, Action<string> performOnEachFolder)
{
performOnEachFolder(path);
EmptyResult result = IsDirectoryEmpty(path);
if (result == EmptyResult.Empty)
yield return path;
if (result == EmptyResult.Error)
yield break;
//A reparse point may indicate a recursive file structure. Cause this to stop the recursion.
//http://blogs.msdn.com/b/oldnewthing/archive/2004/12/27/332704.aspx
if ((File.GetAttributes(path) & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint)
yield break;
IEnumerator<string> it = Directory.EnumerateDirectories(path, "*.*", SearchOption.TopDirectoryOnly).GetEnumerator();
while (it.MoveNext())
{
foreach (string emptyFolder in GetAllEmptyFolders(it.Current, performOnEachFolder))
{
yield return emptyFolder;
}
}
}
private enum EmptyResult
{
Empty = 1,
Used = 2,
Error = 3
}
private static EmptyResult IsDirectoryEmpty(string path)
{
try
{
return !Directory.EnumerateFileSystemEntries(path).Any() ? EmptyResult.Empty : EmptyResult.Used;
}
catch (UnauthorizedAccessException)
{
//We do not want the method to throw as that will cause problems with the iterator block.
return EmptyResult.Error;
}
}
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...}