I am trying to copy a files that i selected from a OpenFileDialog and saved their path into a ListBox.
From the path into the ListBox, I want it to copy it into a specific folder.
So far, it is copying the entire source folder into the destination folder.
My code:
private void button1_Click(object sender, EventArgs e)
{
System.IO.Stream myStream;
OpenFileDialog thisDialog = new OpenFileDialog();
thisDialog.InitialDirectory = "c:\\";
thisDialog.Filter = "All files (*.*)|*.*";
thisDialog.FilterIndex = 2;
thisDialog.RestoreDirectory = true;
thisDialog.Multiselect = true;
thisDialog.Title = "Please Select Attachments!";
if (thisDialog.ShowDialog() == DialogResult.OK)
{
foreach (String file in thisDialog.FileNames)
{
try
{
if ((myStream = thisDialog.OpenFile()) != null)
{
using (myStream)
{
listBox1.Items.Add(file);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
else
{
//do nothing
}
//after selecting the files into the openfile dialog proceed to action the below.
foreach (object item in listBox1.Items)
{
//MessageBox.Show(string.Format("{0}!", listBox1.ToString()));
MessageBox.Show(item.ToString());
string sourceFolder = item.ToString();
string destinationFolder = #"c:\\testing";
//DirectoryInfo directory = new DirectoryInfo(sourceFolder);
DirectoryInfo directoryName = new DirectoryInfo( Path.GetDirectoryName(sourceFolder));
FileInfo[] files = directoryName.GetFiles();
foreach (var file in files)
{
string destinationPath = Path.Combine(destinationFolder, file.Name);
File.Copy(file.FullName, destinationPath);
}
}
}
Any help is mostly welcome. Thanks.
You are reading the whole source directory as many times as many files you selected in the file picker, but you already have the full path of your files in your ListBox, you can simply iterate them over and copy them to the destination like:
string destinationFolder = #"c:\testing";
foreach (var item in listBox1.Items)
{
string sourcePath = item.ToString();
string fileName = Path.GetFileName(sourcePath);
string destinationPath = Path.Combine(destinationFolder, fileName);
File.Copy(sourcePath, destinationPath);
}
Related
I have to show a message, if my folder contains .Dat files and other
extension files. how to do this . Need help appreciated
private void btnChooseFile_Click(object sender, EventArgs e)
{
FileInfo[] files;
FolderBrowserDialog fbd = new FolderBrowserDialog();
//fbd.RootFolder = Environment.SpecialFolder.MyComputer;
fbd.SelectedPath = #txtFilepath.Text.Trim();
if (fbd.ShowDialog() == DialogResult.OK)
{
txtFilepath.Text = fbd.SelectedPath;
if (rbtnOffline.Checked)
{
DefaultManager.OfflineFilePath = #txtFilepath.Text.ToString().Trim();
DirectoryInfo info = new DirectoryInfo(DefaultManager.OfflineFilePath);
files = info.GetFiles("*.dat").OrderBy(p => p.LastWriteTime).ToArray();
if (files.Count() > 0)
{
// MessageBox.Show("no error");
}
else
{
MessageBox.Show("Error, Incorrect capture folder selected", "PGY-SSM", MessageBoxButtons.OK, MessageBoxIcon.Error);
//txtFilepath.Clear();
}
}
else
{
DefaultManager.DumpFilePath = #txtFilepath.Text.ToString().Trim();
}
}}
To determine if there are any other files in the folder, compare the total number of files in the folder with the number of dat files:
int fileCount = info.GetFiles().Length;
int datFileCount = info.GetFiles("*.dat").Length;
if (fileCount != datFileCount)
{
MessageBox.Show("Error, other files found …");
}
I am trying to copy one image from one location to another location using File.Copy() function but it gives the process can not access exception,any one can please help on this bellow is the code block.I have attached screenshot for exception.
private void btnUpload_Click(object sender, EventArgs e)
{
string SourcePath;
string RootDrive;
string DestPath;
string fileName;
fileName = "";
try
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Select Image to Upload";
ofd.Filter = "Jpg|*.jpg|Jpge|*.jpge|Gif|*.gif";
ofd.FileName = null;
if (ofd.ShowDialog() != DialogResult.Cancel)
{
fileName = ofd.FileName;
}
ofd.Dispose();
DestPath = Directory.GetCurrentDirectory() + #"\Uploads\PropertyImages\";
string destFile = System.IO.Path.Combine(DestPath, fileName);
if (!System.IO.Directory.Exists(DestPath))
{
System.IO.Directory.CreateDirectory(DestPath);
}
System.IO.File.Copy(fileName, destFile, true);
}
catch (Exception ae)
{
MessageBox.Show(ae.Message, "Upload Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
It's probably because you are attempting to copy the file to itself. The call to Combine(), as you have it, is just returning fileName. Change the following line:
string destFile = System.IO.Path.Combine(DestPath, fileName);
to
string destFile = System.IO.Path.Combine(DestPath, System.IO.Path.GetFileName(fileName));
Hy everyone,
I would like to copy multiple selected files with openfiledialog to a folder which is defined as #"C:\TestFolder\"+ textBox1.Text. My problem is that somehow the program writes the textBox content in the file name too.
Please find below my code:
private void button3_Click(object sender, EventArgs e)
{
OpenFileDialog od = new OpenFileDialog();
od.Filter = "All files (*.*)|*.*";
od.Multiselect = true;
if (od.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string targetPath = #"C:\TestFolder\"+ textBox1.Text;
string path = System.IO.Path.Combine(targetPath, textBox1.Text);
if (!System.IO.Directory.Exists(targetPath)
{
System.IO.Directory.CreateDirectory(targetPath);
}
foreach (string fileName in od.FileNames)
{
System.IO.File.Copy(fileName, path + System.IO.Path.GetFileName(fileName));
}
}
}
Any input would be appreciated!
Try this one:
string Main_dir = #"C:\TestFolder\";
string Sub_dir = textBox1.Text + #"\";
string targetPath = System.IO.Path.Combine(Main_dir, Sub_dir);
{
if (!System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}
foreach (string fileName in od.FileNames)
System.IO.File.Copy(fileName, targetPath + System.IO.Path.GetFileName(fileName), true);
}
Backslash is missing
#"\"
These things are equivalent.
string targetPath = #"C:\TestFolder\"+ textBox1.Text;
string path = System.IO.Path.Combine(targetPath, textBox1.Text);
I would drop the first one for the Path.Combine call as it is portable and robust when it comes to the separators.
I opened a directory and I read some files in that directory amd made some changes, now I want to save the changes with the same file names at F:\BI\Out\ and keep the original files.
when I added these two lines
var outFilePath = #"F:\BI\Out\" + Path.GetFileName(file);
File.WriteAllText(outFilePath, text);
I was able to save the files under the new folder\Out,
but when I opened them I found that only one file is changed correctly and all the other files the old words are replace by blank space not by the new words.
Can anyone help me Thanks
string text = "";
string[] files;
private void Form1_Load(object sender, EventArgs e)
{
try
{
files = Directory.GetFiles(#"F:\BI\In\", "*.*", SearchOption.AllDirectories);
}
catch (IOException ex)
{
MessageBox.Show(ex.Message);
this.Close();
}
}
private void btnUpdate_Click(object sender, EventArgs e)
{
if (txtEtlPath.Text == "")
{
MessageBox.Show("Please Enter path");
txtEtlPath.Focus();
}
else
{
foreach (string file in files)
{
if (System.IO.File.Exists(file))
{
text = File.ReadAllText(file);
text = text.Replace("Company_Address", txtCompanyAddress.Text + "_BI");
text = text.Replace("Company_Name", txtCompanyName.Text.Trim() + "_BIDW");
text = text.Replace("C:\\BIfolder",cboDrive.Text + txtEtlPath.Text.Trim());
var outFilePath = #"F:\BI\Out\" + Path.GetFileName(file);
File.WriteAllText(outFilePath, text);
}
Within your foreach () loop:
If you want the subfolder structure of the files found, do a replace on the filepath:
var outFilePath = file.Replace(#"F:\BI\In\", #"F:\BI\Out\");
You will need to create the subfolder before you can write the changed file:
new FileInfo(outFilePath)).Directory.Create();
If you don't want the subfolders, you can write directly into the top folder:
var outFilePath = #"F:\BI\Out\" + Path.GetFileName(file);
Writing is simple, just keep in mind there is an optional encoding parameter:
File.WriteAllText(outFilePath, text);
i have application with Listbox and files, each time i press on Add button the default C drive open and i want the application to remember the last path i used
private void btnAdd_Click(object sender, EventArgs e)
{
System.IO.Stream myStream;
OpenFileDialog thisDialog = new OpenFileDialog();
thisDialog.InitialDirectory = "c:\\";
thisDialog.Filter = "(*.snoop, *.pcap, *.cap, *.net)|*.snoop; *.pcap; *.cap; *.net|" + "All files (*.*)|*.*";
thisDialog.FilterIndex = 1;
thisDialog.RestoreDirectory = false;
thisDialog.Multiselect = true; // Allow the user to select multiple files
thisDialog.Title = "Please Select Source File";
thisDialog.FileName = lastPath;
List<string> list = new List<string>();
if (thisDialog.ShowDialog() == DialogResult.OK)
{
foreach (String file in thisDialog.FileNames)
{
try
{
if ((myStream = thisDialog.OpenFile()) != null)
{
using (myStream)
{
listBoxFiles.Items.Add(file);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
}
Save the last directory used in a global variable like this:
private string _lastPath = string.Empty;
then after the file selection initialize it:
if(thisDialog.Filenames.Length > 0)
_lastPath = Path.GetDirectoryName(thisDialog.Filenames[0]);
when you reopen the dialog set the InitialDirectory with this check:
thisDialog.InitialDirectory = (_lastPath.Length > 0 ? _lastPath: "c:\\");
and remove the thisDialog.FileName = lastPath;
EDIT --- UPDATE OF YOUR CODE ---
// This at the global level of your form
private string _lastPath = string.Empty;**
private void btnAdd_Click(object sender, EventArgs e)
{
System.IO.Stream myStream;
OpenFileDialog thisDialog = new OpenFileDialog();
thisDialog.InitialDirectory = (_lastPath.Length > 0 ? _lastPath: "c:\\");
thisDialog.Filter = "(*.snoop, *.pcap, *.cap, *.net)|*.snoop; *.pcap; *.cap; *.net|" + "All files (*.*)|*.*";
thisDialog.FilterIndex = 1;
thisDialog.RestoreDirectory = false;
thisDialog.Multiselect = true; // Allow the user to select multiple files
thisDialog.Title = "Please Select Source File";
thisDialog.FileName = lastPath;
List<string> list = new List<string>();
if (thisDialog.ShowDialog() == DialogResult.OK)
{
if(thisDialog.Filenames.Length > 0)
_lastPath = Path.GetDirectoryName(thisDialog.Filenames[0]);
foreach (String file in thisDialog.FileNames)
{
try
{
if ((myStream = thisDialog.OpenFile()) != null)
{
using (myStream)
{
listBoxFiles.Items.Add(file);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
}
You can use a Visual Studio have the last path value for every execution of the application.
Only have to go to Project Properties->Configuration and add a value descriptor.
Example:
Name = LastPath; Type = string; Scope = User; Value = "Default path";
And then after you rebuild yout application, you can set this property this way:
Settings.Default.LastPath = LastPathSelected;
later, you can retrieve the value with:
thisDialog.InitialDirectory = Settings.Default.LastPath;
thisDialog.InitialDirectory = Path.GetDirectoryName(lastPath);
Yes, you can use the OpenFileDialog.InitialDirectory property. Note: you are setting the directory and not the file. So be sure to remove the filename from the path.
more info here
remove this line and you have the last path
thisDialog.InitialDirectory = "c:\\";