I have a form with an add button. When clicked, a user selects a file or files from the dialog.
My Goal:
Retrieve the names of all the files that a user selects (from whichever directory their file(s) are in) , copy those files in a specified folder that the user doesn't choose using File.Copy (I hard-code a filepath and filename).
My Issue:
If the user only selects one, this works fine. For example:
string name = System.IO.Path.GetFileName(sfd.FileName);
This grabs the file. Then:
DialogResult dialogResult = MessageBox.Show("Is this published?", "", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
Directory.CreateDirectory("c:\\NewTest\\" + txtAcronym.Text + "\\" + txtMajor.Text + "." + txtMinor.Text + "\\Published");
File.Copy(sfd.FileName, "c:\\NewTest\\" + txtAcronym.Text + "\\" + txtMajor.Text + "." + txtMinor.Text + "\\Published\\" + name);
}
else if (dialogResult == DialogResult.No)
{
Directory.CreateDirectory("c:\\NewTest\\" + txtAcronym.Text + "\\" + txtMajor.Text + "." + txtMinor.Text + "\\NonPublished");
File.Copy(sfd.FileName, "c:\\NewTest\\" + txtAcronym.Text + "\\" + txtMajor.Text + "." + txtMinor.Text + "\\NonPublished\\" + name);
}
I ask the user if the document is published. Based on the answer, it will create a directory and put the file in that directory.
Is it possible to loop through multiple filenames in the openFileDialog and put them all in a folder , rather than just one?
Set the Multiselect to true.
myFileDialog.Multiselect = true;
When the user accepts the selection, you can get them with FileNames property. It returns a string[]. Note the difference with FileName which returns string. You can use a for or foreach to get all the results.
foreach (string file in myFileDialog.FileNames)
{
//do work
}
Related
I want to add the link to my local file into one of the columns of Exported CSV file.So that when user clicks on the link the local file open. I have searched the internet for this but can't find any good solution.
Here is the screenshot of what i try to do -
Suppose when user clicks on File path selected row file full name then upon click i should open the file at that localtion.
My code to generate the CSV file is-
public void GetExportDetailsCSV(ExportInformation ExportInfo)
{
StringBuilder cameraRows = new StringBuilder();
string filePath = ExportInfo.ExportOutputPathAtClient + SLASH_STRING + "ExportDetails.csv";
string columnsNames = "File Name ,File Path" + "\r\n";
if(Directory.Exists(ExportInfo.ExportOutputPathAtClient))
{
try
{
foreach (string newPath in Directory.GetFiles(string.Format("{0}{1}", ExportInfo.ExportOutputPathAtClient, SLASH_STRING), "*" + ExportInfo.VideoFileFormat.ToString(), SearchOption.AllDirectories))
{
FileInfo FileDetails = new FileInfo(newPath);
cameraRows.Append(string.Format("{0},{1}\r\n", FileDetails.Name, FileDetails.FullName));
}
string FinalData = "\nExport Remarks : Simple Export " + "\n\n" + "," + "," + "," + "," + "File Details" + "," + "\r\n" + "\r\n" + columnsNames + "\n " + cameraRows;
using (var stream = System.IO.File.CreateText(filePath))
{
stream.WriteLine(FinalData);
}
}
catch(Exception ex)
{
}
}
}
My question is simple how can i put file location value as a link in my Exported CSV file.
Thankyou!
Try using the Hyperlink function. Check this link
You can try this sample. Open notepad type below the line and save it as CSV.
This,is,demo,"=HYPERLINK(""http://www.google.com/"",""Link"")"
Hopefully, this will solve the problem.
I am trying to to delete file after successful copy.
I want the original file to be deleted after I copied it.
private void button2_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.Filter = "All Files(*.*)|*.*";
if (open.ShowDialog() == DialogResult.OK)
{
string filename = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + id.ToString()+Path.GetExtension(open.FileName);
if (!Directory.Exists(Application.StartupPath + "\\AttachedFiles"))
{
Directory.CreateDirectory(Application.StartupPath + "\\AttachedFiles");
}
File.Copy(open.FileName, Path.Combine(Application.StartupPath + "\\AttachedFiles", filename));
cnx.ExecuteCmd("insert into Attachement values('" + id + "','" + filename + "','" + Path.GetFileName(open.FileName) + "')");
MessageBox.Show("attached success");
listBox1.DataSource = cnx.SelectCmd("select * from Attachement where Accidentid='" + id + "'");
listBox1.DisplayMember = "RealFilename";
listBox1.ValueMember = "Filename";
}
}
To delete a File you can use
File.Delete(filePath)
But why don't move it with a single command instead?
File.Move(filePathSource, filePathDestination);
If you can't delete or move a file, you probably still have a Stream open.
Here a working example, how to use an OpenFileDialog and delete and copy the selected file.
using (File.Create(#"c:\Temp\txt.txt")); // File.Create wrapped in a using() to ensure disposing the stream.
using (OpenFileDialog ofd = new OpenFileDialog())
{
if (ofd.ShowDialog() == DialogResult.OK)
{
File.Copy(ofd.FileName, ofd.FileName + "2.txt");
File.Delete(ofd.FileName);
File.Delete(ofd.FileName + "2.txt");
}
}
Notice, that i wrap a using(...) around the File.Create(). This is because it opens a Stream to the File, which locks it. If you remove the using(...) around the File.Create() the deletion will not work.
To understand why you can't delete your File, you have to search your code for any access to the file.
Here is all I want to do: Every time the button is clicked, an openfile dialog is opened, the user clicks on a picture, then this picture is copied to a specific folder and renamed to a number. Every picture's name in this folder should be a number, but they must all be different. My code so far:
if (openfile.ShowDialog() == DialogResult.OK)
{
try
{
File = Image.FromFile(openfile.FileName);
pictureBox3.Image = File;
int i = 0;
if (System.IO.File.Exists(picturedir + "\\" + i.ToString() + ".png") == true)
{
i++;
MessageBox.Show(picturedir + "\\" + i.ToString() + ".png" + ".....Already Exists.");
}
else if (System.IO.File.Exists(picturedir + "\\" + i.ToString() + ".png") == false)
{
System.IO.File.Copy(openfile.FileName, picturedir + "\\" + i.ToString() + ".png", true);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Of course here, the first picture is copied and renamed to "0.png" but the next pictures are not copied at all, because the "if" gives true. Any ideas ? Thanks.
You could do this:
...
int i = 0;
while (System.IO.File.Exists(picturedir + "\\" + i.ToString() + ".png") == true)
{
i++;
// I wouldn't show that message each time, gonna get pretty old for lots of pics!
}
System.IO.File.Copy(openfile.FileName, picturedir + "\\" + i.ToString() + ".png", true);
...
If you want the next number, you can enumerate the existing files, find the maximum number now in use and add 1. Something like:
var files = Directory.EnumerateFiles(myCurrentDirectory, "*.png");
var fileNumStrings = from file in files select Path.GetFileNameWithoutExtension(file);
var max = 0;
foreach (var fileNumString in fileNumStrings)
{
if (int.TryParse(fileNumString, out var filenum))
{
if (filenum > max)
{
max = filenum;
}
}
}
var nextNum = max + 1;
Ok, so I'm new to C# and don't know what I'm doing wrong.
At the top of the button click event I have this variable:
InformationDump infodump;
infodump = new InformationDump();
After that I have the rest of the code which is meant to path to the user desktop and save whatever is filled out in the textbox's into a separate window (part of the same program):
infodump.richTextBox1.Text = textBox1.Text + ", " + textBox2.Text + ", " + textBox3.Text + ", " + textBox4.Text + ", " + comboBox1.SelectedItem;
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string filename = path + "\\" + DateTime.Now.ToString("HH.mm.ss") + System.Environment.UserName + ".txt";
infodump.richTextBox1.SaveFile(filename, RichTextBoxStreamType.RichText);
Thanks in advance.
This is happening because you are creating an instance of the form (InformationDump) then try to use the RichTextBox instance but the form then will not go through the standard loading and initialization process therefore as I reproduced, the file will be created but will be empty.
It is very interesting, but if you do repeated save it works!
infodump.richTextBox1.SaveFile(filename, RichTextBoxStreamType.RichText);
// zero bytes
infodump.richTextBox1.SaveFile(filename, RichTextBoxStreamType.RichText);
// works!
I have a web service that locates files in a folder (C:\Incoming) and emails them to a specified email address. I want to be able to move that folder, once it has been mailed to another folder (C:\Processed).
I tried using this code below, but it does not work.
string SourceFile = "C:\\Incoming\\" + "" + Year + "" + Month + "" + Day + "";
string destinationFile = "C:\\Processed" + "" + Year + "" + Month + "" + Day + "";
System.IO.File.Move(SourceFile , destinationFile);
I get an error saying that the sourcefile could not be found. I have verified that it does exist and I have access to it.
You are moving folders not file you will need to iterate over files to copy one by one.
string Source = "C:\\Incoming\\" + "" + Year + "" + Month + "" + Day + "";
string destination = "C:\\Processed" + "" + Year + "" + Month + "" + Day + "";
DirectoryInfo di = new DirectoryInfo(Source);
FileInfo[] fileList = di.GetFiles(".*.");
int count = 0;
foreach (FileInfo fi in fileList)
{
System.IO.File.Move(Source+"\\"+fi.Name , destinationFile+"\\"+fi.Name);
}
Use String.Format for one, second use System.IO.File.Exists() to make sure the file is there.
string SourceFile = String.Format("C:\\Incoming\\{0}{1}{2}",Year,Month,Day);
string destinationFile = String.Format("C:\\Processed\\{0}{1}{2}",Year,Month,Day);
if (System.IO.File.Exists(SourceFile) {
System.IO.File.Move(SourceFile , destinationFile);
}