File upload control error - c#

im using a file upload control and here is my code :
//Uploading the image
if (imageUpload.HasFile)
{
try
{
if (imageUpload.PostedFile.ContentType == "image/jpeg")
{
if (imageUpload.PostedFile.ContentLength < 102400)
{
string im = ( "~/User" + "/" + Page.User.Identity.Name + "/" + Page.User.Identity.Name + ".jpeg");
imageUpload.SaveAs(im);
uploadLabel.Text = "";
}
else
{
uploadLabel.Text = "File size must be less than 1024 kb";
}
}
else
{
uploadLabel.Text = "File must be in jpeg/jpg format";
}
}
catch(Exception ex)
{
uploadLabel.Text = "File upload failed becuase: " + ex.Message;
}
}
but im getting an error:
The SaveAs method is configured to require a rooted path, and the path "path" is not rooted.
what am i doing wrong.
thanks

SaveAs() requires an absolute path.
try using Request.PhysicalApplicationPath + "\\User"

The Save method is configured to require an absolute path (starting with X:\..., in some drive).
You should call Server.MapPath to get the absolute path on disk to ~/whatever.

Add Server.MapPath where you declare im
Server.MapPath gives you the absolute path.
string im = Server.MapPath("/User") + "/" + Page.User.Identity.Name + "/" + Page.User.Identity.Name + ".jpeg";

string filename = FileUpload1.FileName.ToString();
if (filename != "")
{
ImageName = FileUpload1.FileName.ToString();
ImagePath = Server.MapPath("Images");
SaveLocation = ImagePath + "\\" + ImageName;
SaveLocation1 = "~/Image/" + ImageName;
sl1 = "Images/" + ImageName;
FileUpload1.PostedFile.SaveAs(SaveLocation);
}
try this may be help ful.......

Related

How to extract file from ZIP archive without the folder using System.IO in c#

In a WinForms project I am trying to extract archive in destination folder, but I not want to extract the folder from archive in destination folder.
I want to extract only the file.
My code:
private void button1_Click(object sender, EventArgs e)
{
string Info = "";
string extractPath = #"D:\dosfiles\SYNOPD\SYNOPD$$.PD\" + comboBox3.SelectedItem.ToString() + #"\" + comboBox2.SelectedItem.ToString() + #"\";
string zipPath = #"D:\dosfiles\" + comboBox1.SelectedItem.ToString() + "_" + comboBox2.SelectedItem.ToString() + "_" + comboBox3.SelectedItem.ToString() + "S" + ".zip";
if (!Directory.Exists(extractPath))
{
Info += "Folder not exists in D:\\dosfiles\\SYNOPD\\SYNOPD$$.PD\\" + comboBox3.SelectedItem.ToString() + #"\" + comboBox2.SelectedItem.ToString() + #"\" + comboBox1.SelectedItem.ToString();
}
else if(Directory.Exists(extractPath))
{
if (Directory.Exists(extractPath))
{
Directory.Delete(extractPath, true);
}
ZipFile.ExtractToDirectory(zipPath, extractPath);
Info += "Your synoptic files has been extracted in D:\\dosfiles\\SYNOPD\\SYNOPD$$.PD\\" + comboBox3.SelectedItem.ToString() + #"\" + comboBox2.SelectedItem.ToString() + #"\" + comboBox1.SelectedItem.ToString() + Environment.NewLine;
}
if (Info != "")
{
MessageBox.Show(Info);
Application.Exit();
}
}
}
}

Export To Disk throws error 'The System cannot find the specified path'

I am using the following code to export a crystal report in pdf format.
if (textBox1.Text == "" | textBox2.Text == "")
{
}
else
{
string filename = "\\" + textBox1.Text + ".pdf";
CreateEmptyFile(filename);
string file = textBox2.Text + "\\" + textBox1.Text + ".pdf";
labelget();
try
{
int idx = dataGridView1.CurrentCell.RowIndex;
string parv = dataGridView1.Rows[idx].Cells[0].FormattedValue.ToString();
ReportDocument wordreport = new ReportDocument();
wordreport.Load(#"C:\\FOLDER\\TESTREPORT.rpt");
wordreport.SetDatabaseLogon("root", "xxxxxxx", localhost, database);
wordreport.Refresh();
wordreport.SetParameterValue("bill_no", parv);
wordreport.SetParameterValue("fromterminal", this.terminal);
wordreport.ExportToDisk(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, file);
}
catch (Exception em)
{
MessageBox.Show("error is: " + em);
}
}
Error Occurs in line wordreport.ExportToDisk saying the system could not find the specified path. I checked the permissions for the path where I created the PDF file, It all looks good.
How do i rectify this error?
I Found the Reason and answer for my question. I missed to add DSN details in admin tools.

FileUpload get file extension

I'm trying to upload a file and change its name below. I need to get the file extension. The code below has a underline under "Path" am I missing a using statement? Or what is the correct syntax for what I'm doing?
if (FileUpload1.HasFile)
try
{
var FileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName).Substring(1);
var newName = DateTime.Now.ToLongDateString();
//Map path to folder
string realpath = Server.MapPath("Pictures\\") + Guid.NewGuid() + FileExtension;
FileUpload1.SaveAs(realpath);
Label1.Text = "File name: " +
FileUpload1.PostedFile.FileName + "<br>" +
FileUpload1.PostedFile.ContentLength + " kb<br>" +
"Content type: " +
FileUpload1.PostedFile.ContentType;
}
catch (Exception ex)
{
//Handle the error
throw ex;
}
else
{
Label1.Text = "You have not specified a file.";
}
FileInfo fi = new FileInfo(fileName);
string ext = fi.Extension;
"Path" am I missing a using statement?
You have to add
using System.IO;
to the list of namespaces
The code you have provided looks fine (and works on my machine).
The only thing I can see that you might be missing is the using statement for System.IO.
Use this code:
string extension=System.IO.Path.GetExtension(file1.FileName);

After deployment image not change

After deployment first time image display and same page next time change the imageurl old image only is there new image not display. this is code i want change anything in code....
protected void btn_Upload_Click(object sender, EventArgs e)
{
Image1.Dispose();
if (FileUpload1.HasFile)
{
if (!string.IsNullOrEmpty(txtDesignNo.Text))
{
Image1.Visible = true;
Image1.Dispose();
Image1.ImageUrl = string.Empty;
filename = System.Web.HttpContext.Current.Server.MapPath("") + "\\Images" + "\\" + txtDesignNo.Text + ".jpg";
// filename =CGlobals.imagePath + txtDesignNo.Text + ".jpg";
// string filename = System.Web.HttpContext.Current.Server.MapPath("") + "\\ImageStorage" + "\\" + 1 + ".jpg";
FileUpload1.SaveAs(filename);
Image1.ImageUrl = "~/Masters/Images/" + txtDesignNo.Text + ".jpg";
// Image1.ImageUrl =CGlobals.imagePath + txtDesignNo.Text + ".jpg";
//Image1.ImageUrl = filename;
}
}
}
Try shift+f5 to force a full refresh. Depending on your browser, this might force the fetching of the new image instead of using the cached version.
Looks like you save the image under \Images\ but then you try to show it from \Masters\Images.
Try changing the upload path to match the imageurl or vice versa.
try to check the image path using firebug. You saved image to image folder, but you are accessing from master\images.

Change filename on file upload in .net (asp)

How to change file name on upload ?
I have such code :
<%# WebHandler Language="C#" Class="Upload" %>
using System;
using System.Web;
using System.IO;
public class Upload : IHttpHandler {
public void ProcessRequest(HttpContext context) {
HttpPostedFile oFile = context.Request.Files["Filedata"];
string newFileName1 = HttpContext.Current.Server.MapPath(#context.Request["orderID"]);
string newFileName2 = HttpContext.Current.Server.MapPath(#context.Request["productCombinationString"]);
string newName;
if(newFileName2 != "" && newFileName2 != null && newFileName2 != "<!--#Ecom:productCombinationString-->") {
newName = newFileName1 + newFileName2 + oFile.ContentType;
} else {
newName = newFileName1 + oFile.ContentType;
}
string sDirectory = HttpContext.Current.Server.MapPath(#context.Request["folder"]);
oFile.SaveAs(sDirectory + "/" + oFile.FileName);
if (!Directory.Exists(sDirectory)) Directory.CreateDirectory(sDirectory);
context.Response.Write("1");
}
public bool IsReusable {
get { return false; }
}
}
And if i change oFile.Filename to newName it does not work ... what is the problem ? :)
Thank you
You can pass your Custom File Name along with Directory to SaveAs Method
oFile.SaveAs(sDirectory + "/" + "abc");
try:
// Get the extension of the uploaded file.
string fileName = Server.HtmlEncode(FileUpload1.FileName);
string extension = System.IO.Path.GetExtension(fileName);
string newName;
if(newFileName2 != "" && newFileName2 != null && newFileName2 != "<!--#Ecom:productCombinationString-->") {
newName = newFileName1 + newFileName2 + extension ;
} else {
newName = newFileName1 + extension ;
}
oFile.SaveAs(sDirectory + "/" + newName );
I haven't tried this code but I do want to point out two things of from the original code:
The first is this order of operations:
oFile.SaveAs(sDirectory + "/" + oFile.FileName);
if (!Directory.Exists(sDirectory)) Directory.CreateDirectory(sDirectory);
I believe it should be this instead. In the above sequence, there is a potential edge case of saving into a non-existing folder. This ensures that the folder is created:
if (!Directory.Exists(sDirectory))
{
Directory.CreateDirectory(sDirectory);
}
oFile.SaveAs(sDirectory + "/" + oFile.FileName);
The other thing is that you might be running into issues with / as the path separator. I think it should be much safer to do something like:
var saveLocation = Path.Combine(sDirectory, oFile.FileName);
oFile.SaveAs(saveLocation);
I hope this helps!
Here is an example i used when saving an image look at the save as section
////saving file in the physical folder;
FileUpload FileUpload1 = file_Image;
string virtualFolder = "~/Resourceimages/";
string physicalFolder = HostingEnvironment.MapPath(virtualFolder);
string PhotoName = ((string)Session["UserName"] + (string)Session["UserSurname"]);
FileUpload1.SaveAs(physicalFolder + PhotoName + FileUpload1.FileName);
string location = virtualFolder + PhotoName + FileUpload1.FileName;
webservice.UpdateResourceImage((int)Session["UserID"], location);
lbl_Result.Text = "Your file " + FileUpload1.FileName + " has been uploaded.";
Image1.Visible = true;
Image1.ImageUrl = location;
string uploadFolder = Request.PhysicalApplicationPath + "UploadFile\\";
if (FileUpload1.HasFile)
{
string extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
FileUpload1.SaveAs(uploadFolder + "Test"+ extension);
Label1.Text = "File uploaded successfully as: " + "Test"+ extension;
}
else
{
Label1.Text = "First select a file.";
}
private string UpdateFilename(string filename)
{
try
{
filename = Server.HtmlEncode(FUJD.FileName);
string extension = System.IO.Path.GetExtension(filename);
filename = filename.Replace(extension, "");
return filename + '-' + DateTime.Now.ToString("yyyyMMddHHmmss") + extension;
}
catch (Exception ex)
{
throw ex;
}
}

Categories

Resources