Saving Uploaded File with Unique Name in Folder - c#

I need to save a file(image) to a folder.
If have an image with name "OrignalName", then its saving in their original name in to my specified folder. I'm using
string filename = Path.GetFileName(fileupload1.PostedFile.FileName);
GenerateFileName(filename);
fileupload1.SaveAs(Server.MapPath("Images" + filename));
How should i change the filename to a unique such as timestamp (yyyymmddMMss)
Any help will be appreciated.

System.IO.FileInfo file = new System.IO.FileInfo(FileUpload1.PostedFile.FileName);
string fname = file.Name.Remove((file.Name.Length - file.Extension.Length));
fname = fname + System.DateTime.Now.ToString("_ddMMyyhhmmss") + file.Extension;

Easily is save file to location and then rename him
string newName = System.DateTime.Now.ToString("ddMMyyhhmmss");
Microsoft.VisualBasic.FileIO.RenameFile(file, newName);

You can try with this code
var newPath = filename + DateTime.Now.ToString("yyyymmddMMss");
fileupload1.SaveAs(Server.MapPath("Images/" + newPath));

You can concate your file name with current date and time before saving it to database like that:
string strtemp = filename + System.DateTime.Now.ToString("ddMMyyhhmmss");

Try the following:
int generatedNo = randomNumber.Next(100, int.MaxValue);
string filePath=Path.Combine(Server.MapPath("~/finaldesign")+generatedNo+".jpg");
imageTosave.Save(filePath, ImageFormat.Jpeg);

Related

Renaming the Copy of a Picture

I'm trying to create an album and what I want to do, is to copy a picture from its original path to a specific folder and rename (the copy) right after.
Here is a piece of my code (note that "picturedir" is a path):
string PCname = Environment.UserName;
Image File;
OpenFileDialog openfile = new OpenFileDialog();
openfile.InitialDirectory = #"C:\Users\" + PCname + #"\Pictures";
if (openfile.ShowDialog() == DialogResult.OK)
{
try
{
File = Image.FromFile(openfile.FileName);
pictureBox3.Image = File;
pictureBox3.Image.Save(picturedir + "\\" + openfile.SafeFileName);
System.IO.File.Move(picturedir + "\\" + openfile.SafeFileName,
picturedir + "\\" + "1");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
As seen in the last line inside the "try", I want to rename the chosen picture, simply to "1". However, this last line gives an error "Cannot create a file when that file already exists". Any ideas?
P.S.: If I do not use the last "try" line: System.IO.File.Move(picturedir + "\\" + openfile.SafeFileName, picturedir + "\\" + "1"); it does copy the chosen picture but it obviously does not rename it at all.
Here is an article about work with files.
From article:
static void Main()
{
string fileName = "test.txt";
string sourcePath = #"C:\Users\Public\TestFolder";
string targetPath = #"C:\Users\Public\TestFolder\SubDir";
// Use Path class to manipulate file and directory paths.
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
// To copy a folder's contents to a new location:
// Create a new target folder, if necessary.
if (!System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}
// To copy a file to another location and
// overwrite the destination file if it already exists.
System.IO.File.Copy(sourceFile, destFile, true);
}
If you use different file names, you get copy with new name.

C# Filter differences from a path

DirectoryPath = C:\Pics
filePath = C:\Pics\Dogs\dog.PNG
newPath should be: Dogs\dog.PNG
How do I get the newPath?
My code snippet is not right
string directoryPath = "C:\\Pics";
string filePath = "C:\\Pics\\Dogs\\dog.PNG";
if (!directoryPath.EndsWith("\\"))
directoryPath = directoryPath + "\\";
string newPath = filePath.Substring(filePath.LastIndexOf(directoryPath) + 1);
Thanks in advance!
Could you append a backslash to the directory path & then in the filepath replace the directory path with an empty string
newPath = filePath.Replace(DirectoryPath + #"\", string.Empty);
If the directoryPath does not match the start of the filePath, then newPath will be unchanged.
I did post this before you edited your code to show the conditional adding of the backslash - so that can be removed in the above code.
The int Index you get from LastIndexOf() will always starts with the rightmost value, in your case 0. You have also to add the String.Lenght for this.
if (filePath.StartsWith(directoryPath))
{
string newPath =
filePath.Substring(filePath.LastIndexOf(directoryPath) + directoryPath.Length + 1);
}
I would first check if filePath contains DirectoryPath,so i'd do something like this:
var newPath=filePath.Contains(DirectoryPath)?filePath.Substring(DirectoryPath.Length + 1)
:filePath;
Or even better,using StartsWith
var newPath=filePath.StartsWith(DirectoryPath)?filePath.Substring(DirectoryPath.Length + 1)
:filePath;

Upload File attached to FileUpload Control to FTP C#

I am trying to upload a file that is attached to a FileUpload control to a folder that is created in FTP. The Folder is getting created without issue but I can't seem to upload the file.
It seems as though my filepath to the source file is incorrect in the line String filePath = Server.MapPath("~" + #"\" + nameToGiveFolder); I have tried multiple variations of the file path but cannot seem to get the file uploaded.
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = FileUpload1.FileName;
string ftphost = WebConfigurationManager.AppSettings["myHost"].ToString();
string u = WebConfigurationManager.AppSettings["u"].ToString();
string p = WebConfigurationManager.AppSettings["p"].ToString();
string nameToGiveFolder = FileUpload1.FileName.ToString().Substring(0, FileUpload1.FileName.ToString().LastIndexOf("."));
string ftpfullpath = "ftp://" + ftphost + "/" + nameToGiveFolder;
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath);
ftp.Method = WebRequestMethods.Ftp.MakeDirectory;
ftp.Credentials = new NetworkCredential(u, p);
FtpWebResponse CreateFolderResponse = (FtpWebResponse)ftp.GetResponse();
if (FileUpload1.HasFile)
{
try
{
Label1.Text = "Has File";
String filePath = Server.MapPath("~" + #"\" + nameToGiveFolder);
FileUpload1.SaveAs(filePath);
}
catch (Exception ex)
{
Label1.Text = ex.ToString();
}
}
else
{
Label1.Text = "No File";
}
}
Use Path.GetFileNameWithoutExtension(). to get the file name
FileUpload1.SaveAs(Server.MapPath(string.Format("~/{0}/{1}", Path.GetFileNameWithoutExtension(FileUpload1.FileName), FileUpload1.FileName)));
Note that you need to give the file name as well, if the file name is abc.jpg, above code try to create folder under your root of the web side called abc and save the file inside that folder with file name abc.jpg
i think your problem of line String filePath = Server.MapPath("~" + #"\" + nameToGiveFolder); is only having folder path at the end. when you call FileUpload1.SaveAs you need to have full file path.
Update
You get the error
System.IO.DirectoryNotFoundException: Could not find a part of the
path
because you don't have directory with the name of file name. I'm not where exactly you want to put the file. if you going to put the file in new directory, you need to create that directory first.
var folderpath = Server.MapPath(string.Format("~/{0}", Path.GetFileNameWithoutExtension(FileUpload1.FileName)));
System.IO.Directory.CreateDirectory(folderpath);
FileUpload1.SaveAs(Path.Combine(folderpath, FileUpload1.FileName));

Adding DateTime to filename during rename

I have found lots of examples of people creating new files and adding the current Datetime then the file extension but what I want to do is look to see if a file currently exists and if it does simply add the current DateTime to the file name but I can't figure out how to maintain the file extension. My current code so far:
public class FileUploadHelper
{
private CoreSiteContext db = new CoreSiteContext();
public Int64 UploadSiteImage(string ContainerName, string NewFileName, HttpPostedFile UploadedFile)
{
string SavePath = #"F:\FFInfoImages\" + ContainerName + #"\";
if (System.IO.File.Exists(SavePath + NewFileName))
{
System.IO.File.Move(SavePath + NewFileName, SavePath + NewFileName + DateTime.Now.ToString("MM_dd_yyyy_hh_mm_ss"));
UploadedFile.SaveAs(SavePath + NewFileName);
}
else
{
UploadedFile.SaveAs(SavePath + NewFileName);
}
using (db)
{
File NewFile = new File()
{
FileName = NewFileName,
ContentType = UploadedFile.ContentType
};
db.Files.Add(NewFile);
db.SaveChanges();
return NewFile.ID;
}
}
}
Appears as if the NewFileName string variable does not get passed in with the filename extension, otherwise most of this should work. Why not get the extension from UploadedFile?
string strNewPath = SavePath + NewFileName + Path.GetExtension(UploadedFile.FileName);
if (System.IO.File.Exists(strNewPath)) {
System.IO.File.Move(strNewPath, SavePath + NewFileName + DateTime.Now.ToString("MM_dd_yyyy_hh_mm_ss") + Path.GetExtension(UploadedFile.FileName));
UploadedFile.SaveAs(strNewPath);
}
else {
UploadedFile.SaveAs(strNewPath);
}
using (db) {
File NewFile = new File() {
FileName = NewFileName + Path.GetExtension(UploadedFile.FileName),
ContentType = UploadedFile.ContentType
};
db.Files.Add(NewFile);
db.SaveChanges();
return NewFile.ID;
}
.NET has built-in methods for safely extracting the different portions of a file name (the file's name and it's extension, respectively). Path exists in the System.IO namespace.
Path.GetExtension
Path.GetFileNameWithoutExtension
Assuming NewFileName is something like myfilename.txt, you could use it like this (untested):
if (File.Exists(SavePath + NewFileName))
{
var name = Path.GetFileNameWithoutExtension(NewFileName);
var ext = Path.GetExtension(NewFileName);
File.Move(SavePath + NewFileName,
SavePath + name + DateTime.Now.ToString("MM_dd_yyyy_hh_mm_ss") + ext);
}
UploadedFile.SaveAs(SavePath + NewFileName);
The following method totally solves your problem
System.IO.Path.GetExtension("Path");
You'd better get the current file name without extension first using System.IO.Path.GetFileNameWithoutExtension("Path") then add the Date Time and then add up the extension anyway.
you can use Path.GetExtension() method to identify the file extension.
Try This:
String strExtension=IO.Path.GetExtension(SavePath + NewFileName);
if (System.IO.File.Exists(SavePath + NewFileName))
{
System.IO.File.Move(SavePath + NewFileName, SavePath + NewFileName + DateTime.Now.ToString("MM_dd_yyyy_hh_mm_ss")+strExtension);
UploadedFile.SaveAs(SavePath + NewFileName);
}
else
{
UploadedFile.SaveAs(SavePath + NewFileName);
}

how upload image to folder and display it

I try to upload image to folder (using FileUpload) by pressing one submit button to whole form. i manage to upload the image to separate folders but i can't display it.
thank you.
String fname;
FileUpload tempFU = new FileUpload();
string path = Server.MapPath(".") + "\\images\\" + ulProj.groupCode;
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
try
{
tempFU = (FileUpload)customerUC.FindControl("CustomerLogoUrlFU");
Directory.CreateDirectory(path);
fname = path + "\\" + tempFU.FileName;
tempFU.SaveAs(fname);
tempCus.logoUrl = fname;
}
catch
{
//return;
}
Points to remember:
you should use tilde ~ operator to represent the current project
root folder.
use System.IO.Path.Combine() to combine your path and filename to get the valid complete path.
you are creating the Directory for the given path 2 times. so remove the later part where you are creating the Directory 2'nd time.
as said in the above comments as your catch block is not having anycode,
remove the try-catch block
Complete Solution:
String fname;
FileUpload tempFU = new FileUpload();
string path = Server.MapPath(#"~\images\" + ulProj.groupCode);
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
tempFU = (FileUpload)customerUC.FindControl("CustomerLogoUrlFU");
fname = System.IO.Path.Combine(path,tempFU.FileName);
tempFU.SaveAs(fname);
tempCus.logoUrl = fname;

Categories