When I save a document file in my solution explorer, I send that doc file through mail then I am wanting to delete the document file. It is giving an error like this: process being
used by another process.
Below please find my code:
protected void btnsubmit_Click(object sender, EventArgs e)
{
if (Label1.Text == txtverifytxt.Text)
{
if (rdoSevice.SelectedItem.Value == "1")
{
PackageType = ddlindPackages.SelectedItem.Text;
}
else if (rdoSevice.SelectedItem.Value == "2")
{
PackageType = ddlCorpPack.SelectedItem.Text;
}
if (ResumeUpload.PostedFile != null)
{
HttpPostedFile ulFile = ResumeUpload.PostedFile;
string file = ulFile.FileName.ToString();
FileInfo fi = new FileInfo(file);
string ext = fi.Extension.ToUpper();
if (ext == ".DOC" || ext == ".DOCX")
{
int nFileLen = ulFile.ContentLength;
if (nFileLen > 0)
{
strFileName = Path.GetFileName(ResumeUpload.PostedFile.FileName);
strFileName = Page.MapPath("") + "\\Attachments\\" + strFileName;
ResumeUpload.PostedFile.SaveAs(strFileName);
}
sendingmail();
FileInfo fi1 = new FileInfo(strFileName);
ResumeUpload.FileContent.Dispose();
Label2.Visible = true;
Label2.Text = "Request sent sucessfully";
fi1.Delete();
//if (File.Exists(strFileName))
//{
// File.Delete(strFileName);
//}
ClearAll(tblOrdernow);
//Response.Redirect("CheckOut.aspx");
}
else
{
Label2.Visible = true;
Label2.Text = "Upload only word documents..";
}
}
else
{
Label2.Visible = true;
Label2.Text = "Do not upload empty document..";
}
}
else
{
Label2.Visible = true;
Label2.Text = "Verify Image not Matched";
Label1.Text = ran();
}
}
The most likely cause is the stream you created from
ResumeUpload.PostedFile.SaveAs
hasn't been closed. You could try to force it by disposing or closing the stream. HttpPostedFile has an InputStream property you can use for this:
InputStream
Gets a Stream object that
points to an uploaded file to prepare
for reading the contents of the file.
Related
I am using C# and a winform and am saving data to a .xlsx on a button click event. I have a unique situation that I am not sure how to code for....
If the form is still displayed and the user clicks the button, I want it to prompt for a file name and save location. BUT if the form has not been closed and the user clicks the button a second time, I want .xlsx to be saved in the same location and with the same filename and over write with no prompt.
This is the syntax I use to prompt for save name and location, but how do I check to determine if a filename/save location has already been input and if it has do not prompt again?
private void btnOne_Click(object sender, EventArgs e)
{
SaveFileDialog save = new SaveFileDialog();
save.InitialDirectory = #"C:\";
save.RestoreDirectory = true;
save.Title = "Select save location file name";
save.DefaultExt = "xlsx";
if (save.ShowDialog() == DialogResult.OK)
{
try
{
var file = new FileInfo(save.FileName);
using (var package = new ExcelPackage(file))
{
package.Save();
}
}
catch { Messagebox.Show("An error has occured"; }
}
}
So, whether the data has a set filename is a part of the state of the class. Inside the class where you have btnOne_Click, just define a string with the filename, defaulted to null:
string filepath = null;
Then, in your btnOne_Click, you want to check for the filepath. If it's not there, open the saveAs dialog. After that, if filepath is set, just save. It will be restructured like this:
private void btnOne_Click(object sender, EventArgs e)
{
if (filepath == null)
{
SaveFileDialog save = new SaveFileDialog();
save.InitialDirectory = #"C:\";
save.RestoreDirectory = true;
save.Title = "Select save location file name";
save.DefaultExt = "xlsx";
if (save.ShowDialog() == DialogResult.OK) {
filepath = save.FileName;
}
}
if (filepath != null)
{
try
{
var file = new FileInfo(filepath);
using (var package = new ExcelPackage(file))
{
package.Save();
}
}
catch { MessageBox.Show("An error has occured"; }
}
}
This logical structure gives you standard behavior for when a user presses a save button. If they cancel the saveAs dialog, then the save is aborted and the filename state is not changed.
Declare this globally:
public string Filename;
Then change your subroutine like this:
private void btnOne_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(Filename))
{
SaveFileDialog save = new SaveFileDialog();
save.InitialDirectory = #"C:\";
save.RestoreDirectory = true;
save.Title = "Select save location file name";
save.DefaultExt = "xlsx";
if (save.ShowDialog() == DialogResult.OK)
{
try
{
Filename = save.FileName;
var file = new FileInfo(save.FileName);
using (var package = new ExcelPackage(file))
{
package.Save();
}
}
catch { MessageBox.Show("An error has occured"); }
}
}
else
{
var file = new FileInfo(Filename);
using (var package = new ExcelPackage(file))
{
package.Save();
}
}
}
I got finally, how to download the file using the path. But I was wondering how can I keep the file name only on the grid view. While I need the full path for downloading.
On debugging I came to see that I cannot keep file name only on file upload. Since it is carried to the downloading section. If I keep file name, then file name is carried to the downloading part and the file is not downloaded.
Can anyone help me
Codes
private void UploadAttachment(DataGridViewCell dgvCell)
{
using (OpenFileDialog fileDialog = new OpenFileDialog())
{
//Set File dialog properties
fileDialog.CheckFileExists = true;
fileDialog.CheckPathExists = true;
fileDialog.Filter = "All Files|*.*";
fileDialog.Title = "Select a file";
fileDialog.Multiselect = true;
if (fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string strfilename = fileDialog.FileName;
cncInfoDataGridView.Rows[dgvCell.RowIndex].Cells[1].Value = strfilename;
}
}
}
/// <summary>
/// Download Attachment from the provided DataGridViewCell
/// </summary>
/// <param name="dgvCell"></param>
private void DownloadAttachment(DataGridViewCell dgvCell)
{
string fileName = Convert.ToString(dgvCell.Value);
if (!string.IsNullOrEmpty(fileName))
{
byte[] objData;
FileInfo fileInfo = new FileInfo(fileName);
string fileExtension = fileInfo.Extension;
//show save as dialog
using (SaveFileDialog saveFileDialog1 = new SaveFileDialog())
{
//Set Save dialog properties
saveFileDialog1.Filter = "Files (*" + fileExtension + ")|*" + fileExtension;
saveFileDialog1.Title = "Save File as";
saveFileDialog1.CheckPathExists = true;
saveFileDialog1.FileName = fileName;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string s = cncInfoDataGridView.Rows[dgvCell.RowIndex].Cells[1].Value.ToString();
objData = File.ReadAllBytes(s);
File.WriteAllBytes(saveFileDialog1.FileName, objData);
}
}
}
}
}
Your question is not clear. But if i get you right. Why don't you use use a column for the name and a hidden/0 width column for the file path. Its a grid and therefore you may have many columns. Plus i am thinking the code below should return the full path , unless you trim and can't see where you trim .
string strfilename = fileDialog.FileName;
To get the file name only you can use the Path
string filenameOnly= System.IO.Path.GetFileName(strfilename);
The above should return your file name only you can check here for better understanding.
Add another column and set the width to 0 . Example below
DataGridViewColumn column = dataGridView.Columns[0];
column.Width = 0;
cncInfoDataGridView.Columns.Add(column);
Save your file path in the new column width a 0 width and retrieve during download.
A similar question was asked here.
How to extract file name from file path name?
Dictionary<int, byte[]> _myAttachments;
private void btnUpload_Click(object sender, EventArgs e)
{
try
{
//Throw error if attachment cell is not selected.
//make sure user select only single cell
if (dataGridView1.SelectedCells.Count == 1 && dataGridView1.SelectedCells[0].ColumnIndex == 1)
{
UploadAttachment(dataGridView1.SelectedCells[0]);
}
else
MessageBox.Show("Select a single cell from Attachment column", "Error uploading file", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error uploading file", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnDownload_Click(object sender, EventArgs e)
{
//Throw error if attachment cell is not selected.
//make sure user select only single cell
//and the cell have a value in it
if (dataGridView1.SelectedCells.Count == 1 && dataGridView1.SelectedCells[0].ColumnIndex == 1 && dataGridView1.SelectedCells[0].Value != null)
{
DownloadAttachment(dataGridView1.SelectedCells[0]);
}
else
MessageBox.Show("Select a single cell from Attachment column", "Error uploading file", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
//Throw error if attachment cell is not selected.
//make sure user select only single cell
//and the cell have a value in it
if (dataGridView1.SelectedCells.Count == 1 && dataGridView1.SelectedCells[0].ColumnIndex == 1 && dataGridView1.SelectedCells[0].Value != null)
{
DownloadAttachment(dataGridView1.SelectedCells[0]);
}
else
MessageBox.Show("Select a single cell from Attachment column", "Error uploading file", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
private void UploadAttachment(DataGridViewCell dgvCell)
{
using (OpenFileDialog fileDialog = new OpenFileDialog())
{
//Set File dialog properties
fileDialog.CheckFileExists = true;
fileDialog.CheckPathExists = true;
fileDialog.Filter = "All Files|*.*";
fileDialog.Title = "Select a file";
fileDialog.Multiselect = false;
if (fileDialog.ShowDialog() == DialogResult.OK)
{
FileInfo fileInfo = new FileInfo(fileDialog.FileName);
byte[] binaryData = File.ReadAllBytes(fileDialog.FileName);
dataGridView1.Rows[dgvCell.RowIndex].Cells[1].Value = fileInfo.Name;
if (_myAttachments.ContainsKey(dgvCell.RowIndex))
_myAttachments[dgvCell.RowIndex] = binaryData;
else
_myAttachments.Add(dgvCell.RowIndex, binaryData);
}
}
}
private void DownloadAttachment(DataGridViewCell dgvCell)
{
string fileName = Convert.ToString(dgvCell.Value);
//Return if the cell is empty
if (fileName == string.Empty)
return;
FileInfo fileInfo = new FileInfo(fileName);
string fileExtension = fileInfo.Extension;
byte[] byteData = null;
//show save as dialog
using (SaveFileDialog saveFileDialog1 = new SaveFileDialog())
{
//Set Save dialog properties
saveFileDialog1.Filter = "Files (*" + fileExtension + ")|*" + fileExtension;
saveFileDialog1.Title = "Save File as";
saveFileDialog1.CheckPathExists = true;
saveFileDialog1.FileName = fileName;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
byteData = _myAttachments[dgvCell.RowIndex];
File.WriteAllBytes(saveFileDialog1.FileName, byteData);
}
}
}
I'm working with displaying files from the server's Z:/File Directory. The problem is, while the PDF and JPEG/JPG files render correctly inside the Iframe in localhost, when I use the IIS server IP name, 192.168.xxx.xxx:8081/Home.aspx, they do not render. I also have a download button in which the user can.. well download files. The Iframe and the download button points to the same source, but the Iframe does not return/display the file correctly. It just shows blank.
Here is an example of the source URL: \192.168.xxx.xxx\Z$\File Directory\PDF Files\cyber.pdf.
Oh and BTW, I also map them to the Iframe and download button dynamically.
protected string GetPath(TreeNode treenode)
{
string[] array = new string[100];
string path = string.Empty;
int depth = treenode.Depth;
TreeNode node = new TreeNode();
node = treenode;
array[0] = node.Value;
for (int i = 1; i <= depth; i++)
{
array[i] = node.Parent.Value;
node = node.Parent; ;
}
//path = "~/";
path = #"\\192.168.3.12\Z$\";
for (int i = depth; i >= 0; i--)
{
if (Path.GetExtension(array[i].ToString()) == string.Empty)
{
//path += array[i].ToString() + "/";
path += array[i].ToString() + #"\";
}
else
path += array[i].ToString();
}
return path;
}
protected void trvNews_SelectedNodeChanged(object sender, EventArgs e)
{
try
{
if (trvNews.SelectedNode.Expanded == true)
{
trvNews.SelectedNode.Collapse();
trvNews.SelectedNode.Selected = false;
}
else if(trvNews.SelectedNode.Expanded == false)
trvNews.SelectedNode.Expand();
if (trvNews.SelectedNode.ChildNodes.Count == 0)
{
if (Path.GetExtension(trvNews.SelectedNode.Text) == string.Empty)
{
hfPath.Value = GetPath(trvNews.SelectedNode);
//ListDirectory(trvNews, Server.MapPath(hfPath.Value), "NoChild");
ListDirectory(trvNews, hfPath.Value, "NoChild");
Session["Count"] = "Enabled";
}
else
{
string test2 = Path.GetFullPath(hfPath.Value);
string path = hfPath.Value + trvNews.SelectedNode.Text;
//site = "DocumentViewer.aspx?=" + Path.GetFileName(path);
string url = "DocumentViewer.aspx?=" + Path.GetFileName(path);
Session["Path"] = path;
//ClientScript.RegisterStartupScript(typeof(Page), "Sigma", "open_win()", true);
ScriptManager.RegisterClientScriptBlock(this, GetType(), "newpage", "open_win('" + url + "');", true);
Session["Count"] = "Enabled";
}
}
string test = Session["Count"].ToString();
if (Session["Count"].ToString() == "Enabled")
btnBack.Visible = true;
}
catch (Exception ex)
{
LogError(ex, "User");
}
}
This is the code in the first page as the user clicks the file to view/download it. The next page is..
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
string path = Session["Path"].ToString();
int length = path.Length;
lblHead.Text = Path.GetFileName(path);
System.IO.FileInfo file = new System.IO.FileInfo(Session["Path"].ToString());
if (Path.GetExtension(path) == ".pdf")
{
pnlPdf.Visible = true;
if (Session["FromNews"] != null)
framePdf.Attributes["src"] = FormulatePathPDFNews(path);
else
{
framePdf.Attributes["src"] = "\\\\" + file.FullName;
}
}
else if (Path.GetExtension(path) == ".jpeg" || Path.GetExtension(path) == ".jpg")
{
pnlJpeg.Visible = true;
//imageJpeg.Attributes["src"] = FormulatePath(path);
imageJpeg.Attributes["src"] = file.FullName;
}
}
}
catch (Exception ex)
{
LogError(ex, "User");
}
}
The download button for this is:
protected void btnDownload_Click(object sender, EventArgs e)
{
try
{
if (Path.GetExtension(Session["Path"].ToString()) != null)
{
System.IO.FileInfo file = new System.IO.FileInfo(Session["Path"].ToString());
if (file.Exists)
{
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
Response.End();
}
else
Response.Write("This file does not exist.");
}
}
catch (Exception ex)
{
LogError(ex, "User");
}
}
They are working perfectly fine in localhost, but does not display when in IIS server. Any tips?
Most of the time this would indicate that the path cannot be found or the folder required permissions.
The site will run under a specific user (Look at the Identity in the Application Pool), that user will need permissions to the folder.
i have created a small ftp program in c# using winforms but when i try to create this in wpf it is showing me an error "Value cannot be null. Parameter name:fileName", The code works fine in winform.
here is the code:
public partial class Ftp : UserControl
{
string filePath;
public Ftp()
{
InitializeComponent();
}
//Clear TextBox when clicked
#region textBox clear
public void TextBox_GotFocus(object sender, RoutedEventArgs e)
{
//TextBox tb = (TextBox)sender;
//tb.Text = string.Empty;
//tb.GotFocus -= TextBox_GotFocus;
}
#endregion
//Open File Dialog
private void browser_click(object sender, RoutedEventArgs e)
{
#region File Dialog
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.CheckFileExists = true;
dlg.DefaultExt = ".txt";
dlg.Filter = "JPEG Files (*.txt)|*.txt|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif";
dlg.FileName = "";
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
// Open document
string filename = dlg.FileName;
pathtext.Text = filename;
}
#endregion
}
//Upload the File to FTP
private void Upload_click(object sender, RoutedEventArgs e)
{
#region Upload files
if (filePath == "")
{
MessageBox.Show("Please Select The File To Upload..");
}
else
{
browser.IsEnabled = false;
try
{
FileInfo fileInfo = new FileInfo(filePath);
string fileName = fileInfo.Name.ToString();
WebRequest requestFTP = WebRequest.Create("ftp://" + hosttext.Text + "/" + fileName);
requestFTP.Credentials = new NetworkCredential(usertext.Text, passtext.Password);
requestFTP.Method = WebRequestMethods.Ftp.UploadFile;
FileStream fStream = fileInfo.OpenRead();
int bufferLength = 2048;
byte[] buffer = new byte[bufferLength];
Stream uploadStream = requestFTP.GetRequestStream();
int contentLength = fStream.Read(buffer, 0, bufferLength);
while (contentLength != 0)
{
uploadStream.Write(buffer, 0, contentLength);
contentLength = fStream.Read(buffer, 0, bufferLength);
}
uploadStream.Close();
fStream.Close();
requestFTP = null;
MessageBox.Show("File Uploading Is SuccessFull...");
}
catch (Exception ep)
{
MessageBox.Show("ERROR: " + ep.Message.ToString());
}
browser.IsEnabled = true;
filePath = "";
hosttext.Text = usertext.Text = passtext.Password = pathtext.Text = "";
}
#endregion
}
}
You never set your filePath variable, so it's null. In browser_click you need to do something like
if (result == true)
{
// Open document
string filename = dlg.FileName;
filePath = filename; //added this line
pathtext.Text = filename;
}
Also, you think you have handled your invalid string here:
if (filePath == "")
but at that point filePath = null.
Instead, use if (string.IsEmptyOrNull(filePath))
If I set path = "C:\\MSREAD.txt"; and Click on SaveAs Menu Item ,it saves Filetext,But If I dont give the String path and save it from saveFD.FileName it doesnt work.Please help me with this issue.
Thanks a lot
public void SaveToFile()
{
String SavedFile = "";
saveFD.InitialDirectory = #"C:";
saveFD.Title = "Save a Text File";
saveFD.FileName = "";
RichTextBox richTextBox1 = new RichTextBox();
saveFD.Filter = "Text Files|*.txt|All Files|*.*";
try
{
if (saveFD.ShowDialog() != DialogResult.Cancel)
{
SavedFile = saveFD.FileName;
path = SavedFile.ToString();
//path = "C:\\MSREAD.txt";
MessageBox.Show(path);
richTextBox1.SaveFile(path, RichTextBoxStreamType.PlainText);
SaveMyTextBoxContents(path);
}
}
catch(Exception e)
{
MessageBox.Show(e.ToString());
}
}
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveToFile();
}
public void SaveMyTextBoxContents(string path)
{
if (listBoxItems.SelectedIndex == -1)
{
if (rdBtnSlow.Checked && rdBtnNo.Checked)
{
using (StreamWriter outputFile = new StreamWriter(path))
{
foreach (string item in listBoxItems.Items)
{
saveAllText = slowNo + " " + item;
outputFile.WriteLine(saveAllText);
}
}
}
}
}
Here is your problem:
richTextBox1.SaveFile(path, RichTextBoxStreamType.PlainText);
SaveMyTextBoxContents(path);
You first save the richTextBox text to file, but then override the same file with SaveMyTextBoxContents, However the file is empty because of SaveMyTextBoxContents method will only save something if some conditions are true "not selected item and both check boxes are checked", and the listBoxItems.Items.Count > 0 which apparently not the case