FileUpload get file extension - c#

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);

Related

How to add local file link to Exported CSV file using C#

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.

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.

ASP.NET: Uploading files error "The given path's format is not supported"

I'm trying to save files
string path= "~/Pre/IntraExtra/" + Session["id"].ToString() + "_" + FileUpload1.FileName;
FileUpload11.SaveAs(Server.MapPath(path));
but it gives this error "The given path's format is not supported."
It is working now ..
I just removed the (~/) , Thank you all
for example if I had code that was set like the following on my end it works.. also notice the # symbol I am using .. this is for a literal file path this way I don't have to use "\ in the file path.. try the following code as see if it works.. replace with your code variables.
if (FileUpload1.HasFile)
{
fname = FileUpload1.FileName;
spath = "~\Pre\IntraExtra\" + FileUpload1.FileName;
fpath = Server.MapPath("Uploaded");
fpath = fpath + #"\" + FileUpload1.FileName;
desc = TextBox2.Text;
if (System.IO.File.Exists(fpath))
{
Label1.Text = "File Name already exists!";
return;
}
else
{
FileUpload1.SaveAs(fpath);
}
}
Maybe try to use the Path.Combine method:
string path= "~/Pre/IntraExtra/" + Session["id"].ToString() + "_"; ;
string combinedPath = System.IO.Path.Combine(path, FileUpload1.FileName);
FileUpload11.SaveAs(Server.MapPath(combinedPath));
If this does not work, then could you give us the filename and path?
It is working now .. I just removed the (~/) , Thank you all

Limit file types to be uploaded

I want to limit the types of files that are uploaded to my site. Im using this function below. Would I write if statements for .jpg || .gif || .jpeg || .png.
I don't want people uploading exe's. What is the best way to do this?
if (FileUpload1.HasFile)
try
{
var FileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName);
var Myguid = Guid.NewGuid().ToString("N");
//Check to make sure its an allowable file to be uploaded???????????
var newName = Guid.NewGuid() + FileExtension;
//Map path to folder
string realpath = Server.MapPath("Pictures\\") + newName;
//FileUpload1.SaveAs("C:\\Users\\josh\\Desktop\\JaysVersion\\PicRatingSite\\PicRatingSite\\Pictures" + FileUpload1.FileName);
FileUpload1.SaveAs(realpath);
Label1.Text = "File name: " +
FileUpload1.PostedFile.FileName + "<br>" +
FileUpload1.PostedFile.ContentLength + " kb<br>" +
"Content type: " +
FileUpload1.PostedFile.ContentType;
InsertMembers insert = new InsertMembers();
int age = Int32.Parse(txtAge.Text);
insert.InsertNewMember(txtEmail.Text, Myguid, txtName.Text, txtCity.Text, txtState.Text, txtDescription.Text, age, gender);
//Get Member Id to Insert into Pictures table
GetMemberInfo GetID = new GetMemberInfo();
int UMemberId = GetID.GetMemberId(Myguid);
Displayme.Text = newName.ToString();
//Now that i have member Id Lets insert new picture into picture table
Picture InsertnewPictures = new Picture();
int insertpics = InsertnewPictures.InserNewPicture(UMemberId, newName, 0);
}
catch (Exception ex)
{
//Handle the error
throw ex;
}
else
{
Label1.Text = "You have not specified a file.";
}
Do NOT trust the filename the user provides. It's trivial to hack, and someone can easily do "rename nastyvirus.exe cutekittens.jpg" prior to upload. You must user server-side mime type detection to ensure that you really did get an image. Same goes for the MIME type provided by the remote browser. It can also be trivially forged and make "nastyvirus.exe" show up as "text/plain".
you can filter the type of the file to be upload using a switch statement
var FileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName);
switch(FileExtension.ToLower())
{
case".jpg":
case".png":
case".gif":
case".jpeg":
break;
default:
Response.Write("this file type is not allowed");
return;
}

File upload control error

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.......

Categories

Resources