I am trying to upload files with same names to the server using GUID, but its not working and is still replacing the old files, can anybody help me by telling where I am making the mistake?
here is y code to upload:
protected void btnAddExpenditure_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string FileName = FileUpload1.PostedFile.FileName;
if (File.Exists(FileName))
{
FileName = Guid.NewGuid() + FileName;
}
//check file Extension & Size
int filesize = FileUpload1.PostedFile.ContentLength;
if (filesize > (20 * 1024))
{
Label1.Text = "Please upload a zip or a pdf file";
}
string fileextention = System.IO.Path.GetExtension(FileUpload1.FileName);
if (fileextention.ToLower() != ".zip" && fileextention.ToLower() != ".pdf")
{
Label1.ForeColor = System.Drawing.Color.Green;
Label1.Text = "Please upload a zip or a pdf file";
}
else
{
string ReceiptFileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
//save file to disk
FileUpload1.SaveAs(Server.MapPath("Reciepts/" + ReceiptFileName));
}
string FileName = FileUpload1.PostedFile.FileName;
if (File.Exists(FileName))
{
FileName = Guid.NewGuid() + FileName;
}
...
string ReceiptFileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
Here's your problem. You're creating a new string variable that holds the file name (FileName). If it exists, you modify FileName with a new GUID. But at the very end...
string ReceiptFileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
you're still using the original FileUpload1.PostedFile.FileName. This should be changed to
string ReceiptFileName = Path.GetFileName(FileName);
EDIT: Reading through the code again, I think you may have other problems as well. Assuming that FileUpload1.PostedFile.FileName is a full path (i.e. C:\Folder\File.txt), then
FileName = Guid.NewGuid() + FileName;
would result in something like 123-4321-GUIDC:\Folder\File.txt
I doubt that's what you want. You might want to flip that around
FileName = FileName + Guid.NewGuid();
Related
Currently i am taking in multiple .txt files from a directory i have specified (sourceDirectory). I am generating new .csv files with the same name as the .txt files - one .csv file for each .txt file.
However i want to generate these new files in another directory which i have specified (directoryPath). If i run my program once it creates these files in the initial directory, however if i run my program again it now generates the files in the destination directory.
The following is my code where i complete the above:
static void Main(string[] args)
{
string sourceDirectory = #"C:directoryWhereTXTFilesAre";
var txtFiles = Directory.EnumerateFiles(sourceDirectory, "*.txt", SearchOption.AllDirectories);
foreach (string currentFile in txtFiles)
{
readFile(currentFile);
}
string directoryPath = #"C:\destinationForCSVFiles";
}
I then create the new .csv files name based on the original .txt file like this:
static FileStream CreateFileWithUniqueName(string folder, string fileName, int maxAttempts = 1024)
{
var fileBase = Path.GetFileNameWithoutExtension(fileName);
var ext = Path.GetExtension(fileName);
// build hash set of filenames for performance
var files = new HashSet<string> (Directory.GetFiles(folder));
for (var index = 0; index < maxAttempts; index++)
{
// first try with the original filename, else try incrementally adding an index
var name = (index == 0)
? fileName
: String.Format("{0} ({1}){2}", fileBase, index, ext);
// check if exists
var fullPath = Path.Combine(folder, name);
string CSVfileName = Path.ChangeExtension(fullPath, ".csv");
if (files.Contains(CSVfileName))
continue;
// try to create the file
try
{
return new FileStream(CSVfileName, FileMode.CreateNew, FileAccess.Write);
}
catch (DirectoryNotFoundException) { throw; }
catch (DriveNotFoundException) { throw; }
catch (IOException)
{
}
}
I don't see why it's creating the .csv files initially in the same directory that the .txt files are in and then second time i run my code it creates them in the directoryPath.
Desired output: sourceDirectory left as it is with only .txt files and directoryPath to hold the .csv files.
The only other place i call CreateFileWithUniqueName is within my readFile method, the code is below:
using (var stream = CreateFileWithUniqueName(#"C:destinationFilePath", currentFile))
{
Console.WriteLine("Created \"" + stream.Name + "\"");
newFileName = stream.Name;
Globals.CleanedFileName = newFileName;
}
It seems that you are passing the full filename of the source file. This confuses the Path.Combine inside the CreateFileWithUniqueFilename because you are falling in this subtle remarks found on the documentation of Path.Combine
paths should be an array of the parts of the path to combine. If the
one of the subsequent paths is an absolute path, then the combine
operation resets starting with that absolute path, discarding all
previous combined paths.
You can fix it easily with
using (var stream = CreateFileWithUniqueName(#"C:\destinationFilePath",
Path.GetFileName(currentFile)))
{
Console.WriteLine("Created \"" + stream.Name + "\"");
newFileName = stream.Name;
Globals.CleanedFileName = newFileName;
}
Or better extract the filename without path inside the CreateFileWithUniqueName
static FileStream CreateFileWithUniqueName(string folder, string fileName, int maxAttempts = 1024)
{
var fileBase = Path.GetFileName(fileName);
fileBase = Path.GetFileNameWithoutExtension(fileBase);
var ext = Path.GetExtension(fileBase);
also, you should build your CSVfileName using the cleaned filename
var name = (index == 0)
? String.Format("{0}{1}", fileBase, ext);
: String.Format("{0} ({1}){2}", fileBase, index, ext);
var fullPath = Path.Combine(folder, name);
string CSVfileName = Path.ChangeExtension(fullPath, ".csv");
if (files.Contains(CSVfileName))
continue;
HttpPostedFile file = context.Request.Files[j];
string fileName = file.FileName;
string fileExtension = System.IO.Path.GetExtension(filepath + file.FileName);
if (!string.IsNullOrEmpty(fileName)
{
string pathToSave_100 = HttpContext.Current.Server.MapPath(filepath) + fileName + fileExtension;
if (File.Exists(pathToSave_100))
{
File.Delete(pathToSave_100);
file.SaveAs(pathToSave_100);
}
else
{
file.SaveAs(pathToSave_100);
}
}
You can do like this:
string strFileExtension = Path.GetExtension(file.FileName);
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));
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);
}
string Newfilename;
string Defaultfilename;
protected void btnup_Click(object sender, EventArgs e)
{
if (ASPxUploadControl1.HasFile)
{
string fileExt =
Path.GetExtension(ASPxUploadControl1.FileName);
if (fileExt == ".xls" || fileExt == ".xlsx")
try
{
string extension = Path.GetExtension(ASPxUploadControl1.FileName);
string id = Guid.NewGuid().ToString();
string fileLocation = string.Format("{0}/{1}{2}", Server.MapPath("upload/"), id, extension);
ASPxUploadControl1.SaveAs( fileLocation );
StatusLabel.Text = "Upload status: File uploaded!";
Newfilename = fileLocation;
Defaultfilename = Path.GetFileName(ASPxUploadControl1.FileName);
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
else
{
StatusLabel.Text = "Please choose excel file";
}
}
}
I am trying to assign values to Newfilename and Defaultfilename (inside "try", after naming uploaded file), but they stay empty.
Where I'm wrong?
Refactor your code and think about the process that you want .. then Debug the Code.. Test it.. and if you have an Issue then edit your post.. that's what I suggest..
If statements should be wrapped with in a code block "{ }" same way that you have Try {} a good rule of thumb for even readability would be to wrap everthing around {} if you have If Else otherwise it makes if hard to read as well as lend assistance.
inside your code where you are declaring the following, make them variables within the method itself
string fileExt = string.Empty;
string extension = string.Empty;
string id = string.Empty;
string fileLocation = string.Empty;
so your method would look like this
protected void btnup_Click(object sender, EventArgs e)
{
string fileExt = string.Empty;
string extension = string.Empty;
string id = string.Empty;
string fileLocation = string.Empty;
if (ASPxUploadControl1.HasFile)
{
fileExt = Path.GetExtension(ASPxUploadControl1.FileName);
if (fileExt == ".xls" || fileExt == ".xlsx")
{
try
{
extension = Path.GetExtension(ASPxUploadControl1.FileName);
id = Guid.NewGuid().ToString();
fileLocation = string.Format("{0}/{1}{2}", Server.MapPath("upload/"), id, extension);
ASPxUploadControl1.SaveAs( fileLocation );
StatusLabel.Text = "Upload status: File uploaded!";
Newfilename = fileLocation;
Defaultfilename = Path.GetFileName(ASPxUploadControl1.FileName);
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
else
{
StatusLabel.Text = "Please choose excel file";
}
}
}
Path.GetExtension returns null if the passed value is null and returns string.Empty if the passed value doesn't have an extension.
So please check if the value inside ASPxUploadControl1.FileName actually contains something usefull.
If this is not the case then you'll have to look up where the value is set and debug from there to find out why it's not set.
Can you step through the execution?
Does
NewFilename = fileLocation;
get executed?
If so, what are the values for NewFilename before and after?
This looks like ASP.Net code.
If it is. Is the problem that when you try to use NewFilename elsewhere in the code-behind is is blank.
If you are, then NewFilename may need to be saved to the session to allow you to use it.
hth,
Alan.