Change filename on file upload in .net (asp) - c#

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

Related

How to Rename C# files being moved from source to destination folders using prefix of directory name on each file?

In C# while moving files from source to destination folders, how to rename the destination file with prefix of directory name to each file?
static void Main(string[] args)
{
string sourceFolder = #"C:\Source";
string destinationFolder = #"C:\Destination\";
string dirName = Path.Combine(destinationFolder, DateTime.Now.ToString("dd-MM-yyyy"));
Directory.CreateDirectory(dirName);
DirectoryInfo di = new DirectoryInfo(sourceFolder);
string searchXlsPattern = "*.xls*";
try
{
//Getting list of files from Nested sub folders
ICollection<FileInfo> files = di.GetFiles(searchXlsPattern, SearchOption.AllDirectories).Where(file => !file.DirectoryName.Contains("Archive"))
.Select(x => x)
.ToList();
if (files != null && files.Count() > 0)
{
foreach (FileInfo currentfile in files)
{
if (new FileInfo(dirName + "\\" + currentfile.Name).Exists == false)
{
//Renaming old file name to new file Name
string fileDirectoryName = "";
fileDirectoryName = Path.GetDirectoryName(currentfile.FullName);
string replaceSlash = Convert.ToString(fileDirectoryName.Replace("\\", "_"));
string replaceSplChar= replaceSlash.Replace(":", "_");
string fileextension = Path.GetExtension(currentfile.Name);
string fname = currentfile.Name.Replace(fileextension, "");
string newFileName = replaceSplChar.ToString()+ "_" + fname + fileextension;
//Copy the file to destination folder
//tempfile.CopyTo(Path.Combine(destinationFolder, newFileName), true);
//Move the file to destination folder
currentfile.MoveTo(dirName + "\\" + newFileName);
////File.Move(currentfile.DirectoryName + "\\" + currentfile.Name, dirName + "\\" + newFileName);
//File.Move(currentfile.DirectoryName + "\\" + currentfile.Name, dirName + "\\" + newFileName);
}
}
}
else
Console.Write("There is no files in Source");
}
catch (IOException Exception)
{
Console.Write(Exception);
}
}

how to upload one file many times into folder

I want to upload one file many times into folder. Here my code...
foreach (HttpPostedFile postedFile in FileUpload1.PostedFiles)
{
string filename = Path.GetFileName(postedFile.FileName);
string FileExtension = Path.GetExtension(postedFile.FileName);
for(int i = 1; i <= data.Count;i++)
{
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/InvoiceUploads/") + "Invoice "
+ id + "_" + i + FileExtension);
}
}
this code was to upload one file many times, but the problem is that only one file can open perfectly and the other is given an error and it says empty file.
what's the problem that I don't know?
please anybody help me.
Thank You.
void SendFile()
{
foreach (HttpPostedFile postedFile in FileUpload1.PostedFiles)
{
string filename = Path.GetFileName(postedFile.FileName);
string FileExtension = Path.GetExtension(postedFile.FileName);
// Add a delay
Thread.Sleep(100);
for(int i = 1; i <= data.Count;i++){
postedFile.SaveAs(Server.MapPath("~/InvoiceUploads/") + "Invoice " + id + "_" + i + FileExtension);
}
}
}
why FileUpload1.PostedFile.SaveAs? Use HttpPostedFile .SaveAs(...) instead.
foreach (HttpPostedFile postedFile in FileUpload1.PostedFiles)
{
string filename = Path.GetFileName(postedFile.FileName);
string FileExtension = Path.GetExtension(postedFile.FileName);
for(int i = 1; i <= data.Count;i++){
postedFile .SaveAs(Server.MapPath("~/InvoiceUploads/") + "Invoice " + id + "_" + i + FileExtension);
}
}
Need to Change code
foreach (HttpPostedFile postedFile in FileUpload1.PostedFiles)
{
string filename = Path.GetFileName(postedFile.FileName);
string FileExtension = Path.GetExtension(postedFile.FileName);
string CurrDate = DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss");
for(int i = 1; i <= data.Count;i++)
{
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/InvoiceUploads/") +
"Invoice "
+ id + "_" + i + CurrDate + FileExtension);
}
}

Not able to save file from dynamically generated fileupload controls

I have a project wherein fileupload controls are generating dynamically. Using Json, I'm trying to save file in a directory asynchronously. I want to save files with filename using handler template in asp.net 4.0.
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: Sitepath + "Handler/FileUploader.ashx?filename="+strfiles,
secureuri: false,
fileElementClass: "multi",
dataType: "json",
async: false
});
I've added HTTPPostedFile's logic outside FileUploader class as it was throwing error in that.
public class FileUploader : IHttpHandler, IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
string rt = "";
HttpContext.Current.Response.ContentType = "text/HTML";
string urlresponse = HttpContext.Current.Request.Url.ToString();
string tempfiles = "";
string filenames = "";
int convert = urlresponse.IndexOf(",");
urlresponse = urlresponse.Substring(convert + 1);
string[] filesArray = urlresponse.Split(',');
for (int i = 0; i < filesArray.Length; i++)
{
tempfiles = filesArray[i].ToString();
int lstIndex=tempfiles.LastIndexOf("\\");
filenames = filenames + "," + tempfiles.Substring(lstIndex + 1);
}
filenames = filenames.Substring(filenames.IndexOf(',') + 1);
HttpFileCollection uploads = HttpContext.Current.Request.Files;
string b = HttpContext.Current.Request.Url.ToString();
Hashtable hashtable = new Hashtable();
// Declare variable
string OrderFileName = String.Empty;
string OrderIDs =String.Empty;
string TempFolder = String.Empty;
if (HttpContext.Current.Session["OrderID"] != null)
{
OrderIDs = HttpContext.Current.Session["OrderID"].ToString();
string mapPath = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["DocPath"].ToString());
string mapPathUserId = mapPath + "\\" + HttpContext.Current.Session["UserID"];
///
var g = filenames.Split(',');
for (int t = 0; t < g.Length;t++ )
{
var h = g[t];
rt = filesArray[t].ToString();
if (Directory.Exists(mapPathUserId) == false)
{
Directory.CreateDirectory(mapPathUserId);
}
string mapPathCount = mapPathUserId + "/" + OrderIDs;
if (Directory.Exists(mapPathCount) == false)
{
//--------------Begin(Create Directory)----------------------------------------------------------------------------------//
Directory.CreateDirectory(mapPathCount);
//--------------End(Create Directory)----------------------------------------------------------------------------------//
}
TempFolder = mapPathUserId + "/" + "Temp";
if (Directory.Exists(TempFolder) == false)
{
//--------------Begin(Create Directory for temp folder)----------------------------------------------------------------------------------//
Directory.CreateDirectory(TempFolder);
//--------------End(Create Directoryfor temp folder)----------------------------------------------------------------------------------//
}
OrderFileName = h;
hashtable.Add(t.ToString(), OrderFileName);
var see = HttpContext.Current.Server.MapPath(TempFolder + "/" + OrderFileName);
}
Now, path is being created successfully, but file is not getting saved in specified directory. My code to save the file:
for (int i = 0; i < uploads.Count; i++)
{
HttpPostedFile upload = uploads[i];
if (Directory.Exists(mapPathUserId) == false)
{
Directory.CreateDirectory(mapPathUserId);
}
string mapPathCount = mapPathUserId + "/" + OrderIDs;
if (Directory.Exists(mapPathCount) == false)
{
//--------------Begin(Create Directory)----------------------------------------------------------------------------------//
Directory.CreateDirectory(mapPathCount);
//--------------End(Create Directory)----------------------------------------------------------------------------------//
}
/// Create Path for Temp Folder
TempFolder = mapPathUserId + "/" + "Temp";
if (Directory.Exists(TempFolder) == false)
{
//--------------Begin(Create Directory for temp folder)----------------------------------------------------------------------------------//
Directory.CreateDirectory(TempFolder);
//--------------End(Create Directoryfor temp folder)----------------------------------------------------------------------------------//
}
if (upload.ContentLength > 0)
{
if (upload.FileName.Contains(" "))
{
OrderFileName = upload.FileName.Replace(" ", "_");
}
else
{
OrderFileName = upload.FileName;
}
hashtable.Add(i.ToString(), OrderFileName);
upload.SaveAs(TempFolder + "/" + OrderFileName);
}
}
Please help.
You have to make sure you pass a right path, in the server. I would try mapping the path with the MapPath() function:
upload.SaveAs(Server.MapPath(TempFolder + "/" + OrderFileName));

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

C# checkBox_CheckedChanged Referencing in different files

Requirement: I have a windows application written in C# and I'm trying to add a checkbox to it where if it is checked, than the files from the search will be copied into subdirectories based on zip code.
Problem: When I reference addzipdir_checkBox.Equals(true) from MainForm.cs on a different page SearchProcess.cs I get the error: "addzipdir_checkBox does not exist in the current context". What is the proper way to reference the checkBox_CheckedChanged occurence?
Here's the code on MainForm.cs:
private void addzipdir_checkBox_CheckedChanged(object sender, EventArgs e)
{
if (addzipdir_checkBox.Equals(true))
{
Log("Organize files by zip code.");
}
if (addzipdir_checkBox.Equals(false))
{
Log("Don't Organize files by zip code.");
}
}
Here's the code on SearchProcess.cs generating an error:
if (addzipdir_checkBox.Equals(true))
{
// adds the given lead's agentid and zip code to the targetpath string
string targetzipdir = m_sc.get_TargetPath() + "\\" + AgentID + "\\" + ZIP;
// If the given lead's zip code subdirectory doesn't exist, create it.
if (!Directory.Exists(targetzipdir))
{
Directory.CreateDirectory(targetzipdir);
}
targetFileAndPath = m_sc.get_TargetPath() + "\\" + AgentID + "\\" + ZIP + "\\" + fullFileName;
} // end if addzipdir_checkBox.Equals(true)
You need to make sure addzipdir_checkBox is public. For this, you need to use the form editor, select the addzipdir_Checkbox and change the property grid 'Modifiers' item to public or internal.
Then, you need to find a way to reference the instance of this form, something like this:
if (myForm.addzipdir_checkBox.Equals(true))
{
...
...
}
I found that if you right click a variable and click "Go To Definition" it's a lot easier to find where the variable is referenced. I right clicked another variable that was called in through the MainForm and found that they were all called through the SearchCriteria file. I had to bring the addzipdir_checkbox value referenced on the MainForm.cs file through the SearchCriteria.cs file and then call it in the SearchProcess.cs file.
Here's my code on the SearchCriteria.cs file:
public class SearchCriteria
{
private String Corp;
private String OrderNumber;
private String Campaign;
private String City;
private String State;
private String Zip;
private String SourcePath;
private String TargetPath;
private bool SearchOR;
private bool SearchAND;
private bool addzipdirectory_checkBox;
public SearchCriteria()
{
}
public SearchCriteria(String Corp,
String OrderNumber,
String Campaign,
String City,
String State,
String Zip,
String SourcePath,
String TargetPath,
bool SearchOR,
bool SearchAND,
bool addzipdirectory_checkBox)
{
this.Corp = Corp;
this.OrderNumber = OrderNumber;
this.Campaign = Campaign;
this.City = City;
this.State = State;
this.Zip = Zip;
this.SourcePath = SourcePath;
this.TargetPath = TargetPath;
this.SearchOR = SearchOR;
this.SearchAND = SearchAND;
this.addzipdirectory_checkBox = addzipdirectory_checkBox;
}
public bool get_addzipdir_checkBox()
{
return addzipdirectory_checkBox;
}
public void set_addzipdir_checkBox(bool x)
{
addzipdirectory_checkBox = x;
}
}
Here's my code on the Searchprocess.cs file:
// Copy the file if ANY of the search criteria have been met
if (found)
{
m_form.Invoke(m_form.m_DelegateAddString, new Object[] {"FOUND: Order_No: " + Order_No +
" barcode: " + barcode +
" MailerCode: " + MailerCode +
" AgentID: " + AgentID +
" City: " + City +
" State: " + State +
" ZIP: " + ZIP});
//passes values to TransferFile
TransferFile(directory, barcode, AgentID, ZIP);
}
} // end for that finds each matching record
}
// find and copy the file to the target directory string ZIP
private void TransferFile(string sourceDir, string filename, string AgentID, string ZIP)
{
string fullFileName = filename + ".pdf";
string fullFileNameAndPath = sourceDir + "\\" + fullFileName;
string targetFileAndPath;
if (m_sc.get_addzipdir_checkBox()==true)
{
// adds the given lead's agentid and zip code to the targetpath string
string targetzipdir = m_sc.get_TargetPath() + "\\" + AgentID + "\\" + ZIP;
// If the given lead's zip code subdirectory doesn't exist, create it.
if (!Directory.Exists(targetzipdir))
{
Directory.CreateDirectory(targetzipdir);
}
targetFileAndPath = m_sc.get_TargetPath() + "\\" + AgentID + "\\" + ZIP + "\\" + fullFileName;
} // end if addzipdir_checkBox.Equals(true)

Categories

Resources