How to delete file after success copy - c#

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.

Related

Why does WriteLine in C# change my format in Text File?

So I'm writing an app and without any problem I was getting streamwriter to write new lines using the WriteLine. However, when I got to a certain textbox it automatically started indenting. Please see below image and code:
This is under a save button
SaveFileDialog sfd = new SaveFileDialog();
sfd.InitialDirectory = #"C:\DR\Desktop\4-22-18";
sfd.RestoreDirectory = true;
sfd.FileName = "G-12";
sfd.Filter = "txt files(*.txt)|*.txt| Word Files | *.doc";
if (sfd.ShowDialog()==DialogResult.OK)
{
Stream fileStream = sfd.OpenFile();
StreamWriter sw = new StreamWriter(fileStream);
sw.WriteLine(lblDate.Text);
sw.WriteLine(lblTime.Text);
sw.WriteLine("\r");
sw.WriteLine("G-12"+"\t"+ lblNotes.Text + " " + txtNotes.Text);
sw.WriteLine("==========================================");
sw.WriteLine(lblSG.Text+" "+ nmSG.Text);
sw.WriteLine("==========================================");
sw.WriteLine(lblTinWeight.Text + " " + nmTinWeight.Text);
sw.WriteLine(lblKIO3.Text + " "+ nmKIO3Volume.Text);
sw.WriteLine(lblKIO3N.Text + nmKIO3N.Text);
sw.WriteLine(lblTinPercentage.Text + " "+ lblTinPercent.Text);
sw.WriteLine(lblTinGram.Text + lblTinGrams.Text);
sw.WriteLine("==========================================");
sw.WriteLine(lblNeutWeight.Text+nmNeutWeight.Text);
sw.WriteLine(lblNeutVolume.Text+nmNaOHVolume.Text);
sw.WriteLine(lblNeutNormality.Text + nmNaOHNormality.Text);
sw.Close();
}
enter image description here
The text box contains a space. Verify this by looking the value of lblTinWeight.Text (or a different textbox, not sure) in the debugger.

Avoid exception when writing to null file

I'm doing some WPF exercises and I could succesfully write a file with content on it.
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Text file (*.txt)|*.txt";
sfd.ShowDialog();
using (StreamWriter sw = File.CreateText(sfd.FileName))
{
sw.Write(container.Text);
sw.Close();
}
MessageBox.Show("File " + sfd.FileName + " created at " + DateTime.Now.ToString());
container.ResetText();
That using (StreamWriter) is rising the exception.
If I try to save a file, but, close the window before informing a file name , things go bad.
How can I avoid that ? I tried checking if the file is null ( both above and inside the using statement but it still goes off.
You need to check the result of ShowDialog:
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Text file (*.txt)|*.txt";
if (sfd.ShowDialog() == DialogResult.OK)
{
File.WriteAllText(sfd.FileName, container.Text);
MessageBox.Show("File " + sfd.FileName + " created at " + DateTime.Now.ToString());
container.ResetText();
}

Why won't my code upload a file to the specified folder on the web server when using the fileupload control?

Good afternoon. I have an asp.net web forms application using c#. I am having some difficulty getting my code to work properly. The data is uploaded successfully to the sql server database, but the file isn't saved to the specified "Data" folder. any help would be greatly appreciated?
The ID of the fileupload control is "fu_doc_upld". I don't get any errors when using the form, the files just aren't saving to the "Data" folder (or any other folder). Here is the code behind that I'm using:
protected void btn_frm_new_doc_save_close_Click(object sender, EventArgs e)
{
int i = 0;
string filename = fu_doc_upld.FileName;
if (fu_doc_upld.HasFile)
{
while (System.IO.File.Exists(Server.MapPath("~/Data/") + filename))
{
i++;
filename = fu_doc_upld.FileName + " (" + i.ToString() + ")";
fu_doc_upld.PostedFile.SaveAs(Server.MapPath("~/Data/") + filename);
}
}
hdn_filename_txt.Value = (Server.MapPath("~/Data/") + filename);
hdn_doc_uplod_dt_txt.Value = DateTime.Now.ToString();
SqlConnection idrf_cnxn = new SqlConnection("Data Source=WDBSVCPRD01\\SVCDB;Initial Catalog=idrf;Integrated Security=True");
{
SqlCommand new_doc_cmd = new SqlCommand("Insert Into tbl_doc(doc_title, doc_type_list, doc_org_list, doc_dept_list, doc_desc, prior_contract_cd, legal_comp_contract_id, doc_upld_dt, doc_path, vendor_id_fk) Values(LTRIM(RTRIM(#doc_title)), LTRIM(RTRIM(#doc_type_list)), LTRIM(RTRIM(#doc_org_list)), LTRIM(RTRIM(#doc_dept_list)), LTRIM(RTRIM(#doc_desc)), LTRIM(RTRIM(#prior_contract_cd)), LTRIM(RTRIM(#legal_comp_contract_id)), LTRIM(RTRIM(#doc_upld_dt)), LTRIM(RTRIM(#doc_path)), LTRIM(RTRIM(#vendor_id_fk)))", idrf_cnxn);
new_doc_cmd.Parameters.AddWithValue("#doc_title", doc_title_txt.Text);
new_doc_cmd.Parameters.AddWithValue("#doc_type_list", doc_type_ddl.Text);
new_doc_cmd.Parameters.AddWithValue("#doc_org_list", doc_org_ddl.Text);
new_doc_cmd.Parameters.AddWithValue("#doc_dept_list", doc_dept_ddl.Text);
new_doc_cmd.Parameters.AddWithValue("#doc_desc", doc_desc_txt.Text);
new_doc_cmd.Parameters.AddWithValue("#prior_contract_cd", prior_contract_cd_txt.Text);
new_doc_cmd.Parameters.AddWithValue("#legal_comp_contract_id", lgl_comp_cont_id_txt.Text);
new_doc_cmd.Parameters.AddWithValue("#doc_upld_dt", hdn_doc_uplod_dt_txt.Value);
new_doc_cmd.Parameters.AddWithValue("#doc_path", hdn_filename_txt.Value);
new_doc_cmd.Parameters.AddWithValue("#vendor_id_fk", hdn_vendor_id_txt.Value);
idrf_cnxn.Open();
new_doc_cmd.ExecuteNonQuery();
idrf_cnxn.Close();
if (IsPostBack)
{
Response.Redirect("~/Default.aspx");
}
}
}
Any help would be greatly appreciated.
Thanks,
J
You only call SaveAs() when the file exists. You could've found this by placing a breakpoint and stepping through your code.
Move the save out of the loop:
string filename = fu_doc_upld.FileName;
while (System.IO.File.Exists(Server.MapPath("~/Data/") + filename))
{
i++;
filename = fu_doc_upld.FileName + " (" + i.ToString() + ")";
}
fu_doc_upld.PostedFile.SaveAs(Server.MapPath("~/Data/") + filename);
Note that this code will remove the extension if a file already exists. See C#: How would you make a unique filename by adding a number? for a better implementation.

C# saving mulitple filenames from OpenFileDialog

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
}

C# File only copies once

With my filesystemwatcher I check when a file needs to be copied to a 2nd directory. Everytime. So for example I put in test.txt in dir1 and it automatically copies or cuts the file to dir2. Now when I put in test2.txt in dir1, nothing happens. Why is nothing happening the 2nd time?
Edit: It's a Windows Service
Here is my code:
private void fileSystemWatcher1_Created(object sender, System.IO.FileSystemEventArgs e)
{
variable_reset();
cut_copy = ConfigurationManager.AppSettings[#"cut"];
logger("File created> " + e.FullPath + " -Date:" + DateTime.Now);
filepath = Path.Combine(source, e.Name);
name = Path.GetFileNameWithoutExtension(filepath);
extension = Path.GetExtension(e.FullPath);
size = e.Name.Length;
strSelectCmd = "INSERT INTO files (name,size,last_edit,extension) VALUES('" + name + "','" + size + "',now(),'" + extension + "')";
readquery = "select * from files where name='" + name + "'";
Mysql();
postgresql();
Record();
if (string.IsNullOrEmpty(filename) == false)
{
if (Directory.Exists(e.FullPath))
{
copyfolder();
Directory.CreateDirectory(target);
}
else
{
if (WaitForFileAvailable(e.FullPath, TimeSpan.FromSeconds(10)))
{
var file = Path.Combine(source, e.Name);
var copy_file = Path.Combine(target, e.Name);
var destination = Path.Combine(target, Path.ChangeExtension(source, Path.GetExtension(source)));
if ((String.Compare(cut_copy, "cut"))==0)
{
if (File.Exists(file))// Check to see if the file exists.
{ //If it does delete the file in the target and copy the one from the source to the target.
File.Delete(copy_file);
}
File.Move(e.FullPath, Path.Combine(target, e.Name));
}
if ((String.Compare(cut_copy, "copy"))==0)
{
if (File.Exists(file))// Check to see if the file exists.
{ //If it does delete the file in the target and copy the one from the source to the target.
File.Delete(copy_file);
}
File.Copy(e.FullPath, Path.Combine(target, e.Name));
}
}
else // The file failed to become available within 10 seconds.
{
logger("Copy has failed reason: File is being used by another program");
}
}
}
else
{
query = "INSERT INTO files (name,size,last_edit,extension) VALUES('" + name + "','" + size + "',now(),'" + extension + "')";
Mysql();
}
}

Categories

Resources