I have been trying to upload images via a file upload control. The file is not being uploaded and I keep getting the following error:"Cannot access a closed file."
I am unsure as to why I am getting this error, any assistance would be appreciated.
My code: First is the code that grabs the image and creates the 'preview'
protected void btnupload_Click(Object sender, EventArgs e)
{
Session["Image"] = flupGalImg.PostedFile;
Stream fs = flupGalImg.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
byte[] bytes = br.ReadBytes((Int32)fs.Length);
string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
imgGalImg.ImageUrl = "data:image/png;base64," + base64String;
imgGalImg.Visible = true;
}
My code that calls my business logic code:
else if(btnaddedit.Text == "Add item")
{
if(txtItemTitle.Text != "")
{
if(txtItemDescription.Text != "")
{
if(Session["Image"] != null)
{
HttpPostedFile postedFile = (HttpPostedFile)Session["Image"];
int alb;
int.TryParse(hdnAlbId.Value, out alb);
if(newsLogic.CreateNewGalleryItem(txtItemTitle.Text, txtItemDescription.Text, alb, postedFile) == true)
{
// Do something.
}
}
}
}
}
And finally my business logic code:
// create gallery item
[System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Insert, true)]
public bool CreateNewGalleryItem(string itemTitle, string itemDescription, int itemAlbum, HttpPostedFile itemFile)
{
string folderpath = #"~/Images/GalleryImages/";
string filename = Path.GetFileName(itemFile.FileName.ToString());
bool itemCreated = false;
string itemImgPath;
try
{
itemImgPath = Path.Combine(folderpath + filename);
string itemImgUploadPath = Path.Combine(HttpContext.Current.Server.MapPath(folderpath) + filename);
itemFile.SaveAs(itemImgUploadPath);
galAdp.CreateGalleryItem(itemTitle, itemDescription, itemImgPath, itemAlbum);
itemCreated = true;
}
catch (Exception er)
{
itemCreated = false;
string consmsg = er.Message;
}
return itemCreated;
}
My 'image preview' works just fine. The error is thrown on this line of the business logic: itemFile.SaveAs(itemImgUploadPath);
When I did a google search (well lots of google searches) I read that it may be the file size so I increased the max allowed content in the web.config but nothing changed.
Any ideas as to what I am doing wrong?
Related
i am loading Mp3 Files from folder in Listview. right click option pn listview there is a option of Update tags.when i enter fields data and click update tags it throws ecception Process cant access file it is used by some other process here is my code
private void UpdateTagEditor_RegisterActionEventHandler(object sender, RoutedEventArgs e)
{
var tags = sender as UpdateTags;
string path = tags.targetPath;
string comments = tags.txtTagComment.Text;
string lyrics = tags.txtTagLyrics.Text;
try
{
using (var stream = File.Open(path, FileMode.Open, FileAccess.Write, FileShare.Read))
{
TagLib.Id3v2.Tag.DefaultVersion = 3;
TagLib.Id3v2.Tag.ForceDefaultVersion = true;
TagLib.File tagFile = TagLib.File.Create(path);
tagFile.Tag.Comment = comments;
tagFile.Tag.Lyrics = lyrics;
tagFile.Save();
}
}
catch (Exception exception)
{
}
}
What are you using the Stream for? Nothing it seems. You are trying to create the file twice. Try to remove the stream:
private void UpdateTagEditor_RegisterActionEventHandler(object sender, RoutedEventArgs e)
{
var tags = sender as UpdateTags;
string path = tags.targetPath;
string comments = tags.txtTagComment.Text;
string lyrics = tags.txtTagLyrics.Text;
try
{
TagLib.Id3v2.Tag.DefaultVersion = 3;
TagLib.Id3v2.Tag.ForceDefaultVersion = true;
TagLib.File tagFile = TagLib.File.Create(path);
tagFile.Tag.Comment = comments;
tagFile.Tag.Lyrics = lyrics;
tagFile.Save();
}
catch (Exception exception)
{
}
}
Hi i'm trying to display a preview of an uploaded img in asp.net using the file upload control, i have a preview button where when the user clicks should save the file from the fileupload control into a temp folder on my server and change the imageurl of the imagecontrol to the path of the saved image in the temp folder and display the image on the page after a postback. Here is what i have done:
protected void btnPreview_1_Click(object sender, EventArgs e)
{
if (!imgUpload_1.HasFile)
{
return;
}
string strFileName = Path.GetFileNameWithoutExtension(imgUpload_1.FileName.ToString());
string ext = Path.GetExtension(imgUpload_1.FileName.ToString());
string loc = "temp/";
string strImgFolder = Server.MapPath(loc);
System.Drawing.Image newImage;
FileUpload img = (FileUpload)imgUpload_1;
Byte[] imgByte = null;
try
{
if (img.HasFile && img.PostedFile != null)
{
HttpPostedFile File = imgUpload_1.PostedFile;
imgByte = new Byte[File.ContentLength];
File.InputStream.Read(imgByte, 0, File.ContentLength);
}
}
catch (Exception ex)
{
}
if (imgByte != null)
{
using (MemoryStream stream = new MemoryStream(imgByte, 0, imgByte.Length))
{
newImage = System.Drawing.Image.FromStream(stream);
newImage.Save(strImgFolder + strFileName + ext);
imgPreview.ImageUrl = strImgFolder + strFileName + ext;
imgPreview.AlternateText = strFileName;
}
}
}
I've tried using a handler for this using code i found online and after hours of trying i still couldn't get it to work, i also tried attaching a random number to the end of the imageurl(like so imageurl + "?" + randomnumber to force the page to refresh(That didn't work either) and i also tried:
Response.AddHeader("Cache-Control", "no-cache");
in my page load even and that didn't work either.
I've been at it for hours could someone plz help me out?
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))
I am saving (uploading) file to FTP server using file upload control and .SaveAs method. But after 1st post back session values are lost. Not sure why and any work around this.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["TheUser"] != null)
{
aUser = (clsUser)Session["TheUser"];
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)//continue only if the file control has the file
{
if (Get_and_Show_FileInformation())//if the file information was retrived and loaded into the textboxes
{
//continue with the execution
}
else
{
//error message displyed
}
}
}
protected bool Get_and_Show_FileInformation()
{
if (FileUpload1.HasFile)
{
string fName = FileUpload1.PostedFile.FileName;
string extension = Path.GetExtension(fName);
string FileName = fName.Substring(0, fName.Length - extension.Length);
string dir = uname;
string appPath = Server.MapPath("Uploads/") + dir;
FileInfo MyFileInfo = new FileInfo(appPath);
DirectoryInfo newDirectoryInfo = new DirectoryInfo(appPath);
if (!Directory.Exists(appPath))//if user is uploading to FTP_Upload first time, create a new directory for him/her
{
try
{
FileUpload1.SaveAs(Server.MapPath("~/Uploads/" + dir + "/" + FileName)); // ERROR here, call to this .SaveAs method causes loss of session values (Session["TheUser"])
Image2.ImageUrl = "~/Uploads/" + dir + "/" + FileName;
return true;
}
catch (Exception ex)
{
lbl_Err.Text = "<br/>Error: Error creating and saving into your space!(Error Code:XF05)";
return false;
}
}
else
{
//same code but don't create the directory
}
}
}
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.