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.
Related
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.
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");
}
I can't figure out how the whole thing is built. Do i need to add each link by my self manually ? And if i have 100 links ?
This is a screenshot of what i see in the xmal file
But maybe i can add this links from the code it self ?
The code is long so i will not add it to here.
I got the project from here:
Background File Downloader
If i want to add to the downloader my own links ?
I see in the DownloaderDemo code this part that add the links:
// Get the contents of the rich text box
string rtbContents = new TextRange(rtbPaths.Document.ContentStart, rtbPaths.Document.ContentEnd).Text;
foreach (string line in rtbContents.Split('\n'))
{
String trimmedLine = line.Trim(' ', '\r');
if (trimmedLine.Length > 0)
{
// If the line is not empty, assume it's a valid url and add it to the files list
// Note: You could check if the url is valid before adding it, and probably should do this is a real application
downloader.Files.Add(new FileDownloader.FileInfo(trimmedLine));
}
}
But i don't understand what richTextBox ? I guess it's in the design in the DownloaderDemo.xaml
Still if i want to add my own links to download files ?
This is DownloaderDemo.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace FileDownloaderApp
{
/// <summary>Interaction logic for DownloaderDemo.xaml</summary>
public partial class DownloaderDemo : Window
{
// Creating a new instance of a FileDownloader
private FileDownloader downloader = new FileDownloader();
public DownloaderDemo()
{
InitializeComponent();
CommandBindings.Add(new CommandBinding(ApplicationCommands.Close,
new ExecutedRoutedEventHandler(delegate(object sender, ExecutedRoutedEventArgs args) { this.Close(); })));
downloader.StateChanged += new EventHandler(downloader_StateChanged);
downloader.CalculatingFileSize += new FileDownloader.CalculatingFileSizeEventHandler(downloader_CalculationFileSize);
downloader.ProgressChanged += new EventHandler(downloader_ProgressChanged);
downloader.FileDownloadAttempting += new EventHandler(downloader_FileDownloadAttempting);
downloader.FileDownloadStarted += new EventHandler(downloader_FileDownloadStarted);
downloader.Completed += new EventHandler(downloader_Completed);
downloader.CancelRequested += new EventHandler(downloader_CancelRequested);
downloader.DeletingFilesAfterCancel += new EventHandler(downloader_DeletingFilesAfterCancel);
downloader.Canceled += new EventHandler(downloader_Canceled);
}
public void DragWindow(object sender, MouseButtonEventArgs args)
{
DragMove();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
this.Height -= 30;
}
// A simple implementation of setting the directory path, adding files from a textbox and starting the download
private void btnStart_Click(object sender, RoutedEventArgs e)
{
System.Windows.Forms.FolderBrowserDialog openFolderDialog = new System.Windows.Forms.FolderBrowserDialog();
if (openFolderDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
// Set the path to the local directory where the files will be downloaded to
downloader.LocalDirectory = openFolderDialog.SelectedPath;
// Clear the current list of files (in case it's not the first download)
downloader.Files.Clear();
// Get the contents of the rich text box
string rtbContents = new TextRange(rtbPaths.Document.ContentStart, rtbPaths.Document.ContentEnd).Text;
foreach (string line in rtbContents.Split('\n'))
{
String trimmedLine = line.Trim(' ', '\r');
if (trimmedLine.Length > 0)
{
// If the line is not empty, assume it's a valid url and add it to the files list
// Note: You could check if the url is valid before adding it, and probably should do this is a real application
downloader.Files.Add(new FileDownloader.FileInfo(trimmedLine));
}
}
// Start the downloader
downloader.Start();
}
}
private void btnPause_Click(object sender, RoutedEventArgs e)
{
// Pause the downloader
downloader.Pause();
}
private void btnResume_Click(object sender, RoutedEventArgs e)
{
// Resume the downloader
downloader.Resume();
}
private void btnStop_Click(object sender, RoutedEventArgs e)
{
// Stop the downloader
// Note: This will not be instantantanious - the current requests need to be closed down, and the downloaded files need to be deleted
downloader.Stop();
}
// This event is fired every time the paused or busy state is changed, and used here to set the controls of the interface
// This makes it enuivalent to a void handling both downloader.IsBusyChanged and downloader.IsPausedChanged
private void downloader_StateChanged(object sender, EventArgs e)
{
// Setting the buttons
btnStart.IsEnabled = downloader.CanStart;
btnStop.IsEnabled = downloader.CanStop;
btnPause.IsEnabled = downloader.CanPause;
btnResume.IsEnabled = downloader.CanResume;
// Enabling or disabling the setting controls
rtbPaths.IsReadOnly = downloader.IsBusy;
cbUseProgress.IsEnabled = !downloader.IsBusy;
}
// Show the progress of file size calculation
// Note that these events will only occur when the total file size is calculated in advance, in other words when the SupportsProgress is set to true
private void downloader_CalculationFileSize(object sender, Int32 fileNr)
{
lblStatus.Content = String.Format("Calculating file sizes - file {0} of {1}", fileNr, downloader.Files.Count);
}
// Occurs every time of block of data has been downloaded, and can be used to display the progress with
// Note that you can also create a timer, and display the progress every certain interval
// Also note that the progress properties return a size in bytes, which is not really user friendly to display
// The FileDownloader class provides static functions to format these byte amounts to a more readible format, either in binary or decimal notation
private void downloader_ProgressChanged(object sender, EventArgs e)
{
pBarFileProgress.Value = downloader.CurrentFilePercentage();
lblFileProgress.Content = String.Format("Downloaded {0} of {1} ({2}%)", FileDownloader.FormatSizeBinary(downloader.CurrentFileProgress), FileDownloader.FormatSizeBinary(downloader.CurrentFileSize), downloader.CurrentFilePercentage()) + String.Format(" - {0}/s", FileDownloader.FormatSizeBinary(downloader.DownloadSpeed));
if (downloader.SupportsProgress)
{
pBarTotalProgress.Value = downloader.TotalPercentage();
lblTotalProgress.Content = String.Format("Downloaded {0} of {1} ({2}%)", FileDownloader.FormatSizeBinary(downloader.TotalProgress), FileDownloader.FormatSizeBinary(downloader.TotalSize), downloader.TotalPercentage());
}
}
// This will be shown when the request for the file is made, before the download starts (or fails)
private void downloader_FileDownloadAttempting(object sender, EventArgs e)
{
lblStatus.Content = String.Format("Preparing {0}", downloader.CurrentFile.Path);
}
// Display of the file info after the download started
private void downloader_FileDownloadStarted(object sender, EventArgs e)
{
lblStatus.Content = String.Format("Downloading {0}", downloader.CurrentFile.Path);
lblFileSize.Content = String.Format("File size: {0}", FileDownloader.FormatSizeBinary(downloader.CurrentFileSize));
lblSavingTo.Content = String.Format("Saving to {0}\\{1}", downloader.LocalDirectory, downloader.CurrentFile.Name);
}
// Display of a completion message, showing the amount of files that has been downloaded.
// Note, this does not hold into account any possible failed file downloads
private void downloader_Completed(object sender, EventArgs e)
{
lblStatus.Content = String.Format("Download complete, downloaded {0} files.", downloader.Files.Count);
}
// Show a message that the downloads are being canceled - all files downloaded will be deleted and the current ones will be aborted
private void downloader_CancelRequested(object sender, EventArgs e)
{
lblStatus.Content = "Canceling downloads...";
}
// Show a message that the downloads are being canceled - all files downloaded will be deleted and the current ones will be aborted
private void downloader_DeletingFilesAfterCancel(object sender, EventArgs e)
{
lblStatus.Content = "Canceling downloads - deleting files...";
}
// Show a message saying the downloads have been canceled
private void downloader_Canceled(object sender, EventArgs e)
{
lblStatus.Content = "Download(s) canceled";
pBarFileProgress.Value = 0;
pBarTotalProgress.Value = 0;
lblFileProgress.Content = "-";
lblTotalProgress.Content = "-";
lblFileSize.Content = "-";
lblSavingTo.Content = "-";
}
// Setting the SupportsProgress property - if set to false, no total progress data will be avaible!
private void cbUseProgress_Checked(object sender, RoutedEventArgs e)
{
downloader.SupportsProgress = (Boolean)cbUseProgress.IsChecked;
}
// Setting the DeleteCompletedFilesAfterCancel property - indicates if the completed files should be deleted after cancellation
private void cbDeleteCompletedFiles_Checked(object sender, RoutedEventArgs e)
{
downloader.DeleteCompletedFilesAfterCancel = (Boolean)cbDeleteCompletedFiles.IsChecked;
}
// Close the window when the close button is hit
private void btnClose_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
}
}
You can easily add to the rich text box new download links by creating your own function that takes a new download link path, to append to the text box you do:
richTextBox.AppendText("new string of download link");
You're not sure what rich text box? It is in your .xaml file, it is called rtbPaths. So you could create a new button that executes a dialog box, takes a string and use that string to append to this text box.
It's hard to understand what is being asked here as well, sorry if I got this wrong.
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 this code but it's not working. I've tried several different versions but nothing is working. I'm a newbie and still don't understand everything.
OpenFileDialog filedialog = new OpenFileDialog();
private void button3_Click(object sender, EventArgs e)
{
filedialog.ShowDialog();
filedialog.FileOk += filedialog_FileOk;
}
void filedialog_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
{
using (StreamReader myStream = new StreamReader(filedialog.FileName))
{
string line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = myStream.ReadLine()) != null)
{
listBox1.Items.Add(line);
}
}
}
I think there is a requirement for to much plain text in this editor.
You're adding the event handler after the call to ShowDialog() has returned. Move it to before and it might work.
According to the documentation, FileOK event occurs when Open or Save button is clicked.
You are attaching the event handler inside the click.
You might want to do it on page load or somewhere before the click occurs.
Eg :
OpenFileDialog filedialog = new OpenFileDialog();
protected void Page_Load(object sender, EventArgs e)
{
filedialog.FileOk += filedialog_FileOk;
}
private void button3_Click(object sender, EventArgs e)
{
filedialog.ShowDialog();
}
void filedialog_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
{
using (StreamReader myStream = new StreamReader(filedialog.FileName))
{
string line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = myStream.ReadLine()) != null)
{
listBox1.Items.Add(line);
}
}
}