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);
}
}
Related
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);
}
}
Here is all I want to do: Every time the button is clicked, an openfile dialog is opened, the user clicks on a picture, then this picture is copied to a specific folder and renamed to a number. Every picture's name in this folder should be a number, but they must all be different. My code so far:
if (openfile.ShowDialog() == DialogResult.OK)
{
try
{
File = Image.FromFile(openfile.FileName);
pictureBox3.Image = File;
int i = 0;
if (System.IO.File.Exists(picturedir + "\\" + i.ToString() + ".png") == true)
{
i++;
MessageBox.Show(picturedir + "\\" + i.ToString() + ".png" + ".....Already Exists.");
}
else if (System.IO.File.Exists(picturedir + "\\" + i.ToString() + ".png") == false)
{
System.IO.File.Copy(openfile.FileName, picturedir + "\\" + i.ToString() + ".png", true);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Of course here, the first picture is copied and renamed to "0.png" but the next pictures are not copied at all, because the "if" gives true. Any ideas ? Thanks.
You could do this:
...
int i = 0;
while (System.IO.File.Exists(picturedir + "\\" + i.ToString() + ".png") == true)
{
i++;
// I wouldn't show that message each time, gonna get pretty old for lots of pics!
}
System.IO.File.Copy(openfile.FileName, picturedir + "\\" + i.ToString() + ".png", true);
...
If you want the next number, you can enumerate the existing files, find the maximum number now in use and add 1. Something like:
var files = Directory.EnumerateFiles(myCurrentDirectory, "*.png");
var fileNumStrings = from file in files select Path.GetFileNameWithoutExtension(file);
var max = 0;
foreach (var fileNumString in fileNumStrings)
{
if (int.TryParse(fileNumString, out var filenum))
{
if (filenum > max)
{
max = filenum;
}
}
}
var nextNum = max + 1;
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));
I have a web service that locates files in a folder (C:\Incoming) and emails them to a specified email address. I want to be able to move that folder, once it has been mailed to another folder (C:\Processed).
I tried using this code below, but it does not work.
string SourceFile = "C:\\Incoming\\" + "" + Year + "" + Month + "" + Day + "";
string destinationFile = "C:\\Processed" + "" + Year + "" + Month + "" + Day + "";
System.IO.File.Move(SourceFile , destinationFile);
I get an error saying that the sourcefile could not be found. I have verified that it does exist and I have access to it.
You are moving folders not file you will need to iterate over files to copy one by one.
string Source = "C:\\Incoming\\" + "" + Year + "" + Month + "" + Day + "";
string destination = "C:\\Processed" + "" + Year + "" + Month + "" + Day + "";
DirectoryInfo di = new DirectoryInfo(Source);
FileInfo[] fileList = di.GetFiles(".*.");
int count = 0;
foreach (FileInfo fi in fileList)
{
System.IO.File.Move(Source+"\\"+fi.Name , destinationFile+"\\"+fi.Name);
}
Use String.Format for one, second use System.IO.File.Exists() to make sure the file is there.
string SourceFile = String.Format("C:\\Incoming\\{0}{1}{2}",Year,Month,Day);
string destinationFile = String.Format("C:\\Processed\\{0}{1}{2}",Year,Month,Day);
if (System.IO.File.Exists(SourceFile) {
System.IO.File.Move(SourceFile , destinationFile);
}
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;
}
}