How to rename files before upload - c#

I need to rename every file uploaded using dropzone.js to add a timestamp in his name.
I already tried to do this in the server side, but I can't recover the modified name and set it into the script to do a deletion on server when file is deleted on the browser.
I tried to rename the file int the script too, before upload, but unsuccessful. The functions I tried to use are these:
accept: function (file, done) {
file.name = "timestampHere" + file.name;
done();
}
And this:
sending: function (file, xhr, formData) {
file.name = "heee" + file.name;
}
But in both cases, I can't recover the file name and change it to proceed a file delete on the server when the "Remove" button is fired.
In other words, the file in the server have the time stamp and in browser doesn't.
There's any way to recover the name of the file saved on the server and set it into the script on the browser OR rename the file in the script, before the upload?
My target here is to delete the file on the server too on click of the "Remove" button, after inserting timestamp in the name of the file.

I found an answer here: https://stackoverflow.com/a/17457380/2394172
The context is different of mine, but I've used his concept, creating a repository with an array of objects containing the original name and the server name.
With this I can compare the values and send to the server just the server value.
I hope this can help someone.

Related

File.Copy keeps trying to find a server url by looking for it in my C drive

I am trying to run the File.Copy function so that I can use a template file I have to make a new word document that the code will fill out. Whenever the code gets to the file.copy function I get the error
"IOException: The filename, directory name, or volume label syntax is incorrect : 'C:\Software\DRAT\DRAT*serverpath*\SoftwareReleaseTool\Trunk\ReleaseNotesTemplates\ReleaseNotes1.docx'"
I want the filename to be
"serverpath\SoftwareReleaseTool\Trunk\ReleaseNotesTemplates\ReleaseNotes1.docx"
The first part, "C:\Software\DRAT\DRAT\" is the directory that the project is in. I cannot find out why it keeps looking in this directory for the server link.
I watch the local values before the function is run and they are correct. I get
"serverpath/Fusion/Main\Releases\Notes\VCM-1.1.43-SoftwareReleaseNotes.docx"
for notes.ReleaseNotesPath and
"serverpath/SoftwareReleaseTool/Trunk/ReleaseNotesTemplates/ReleaseNotes1.docx"
for templatePath.
If I use the paths to the same files that are on my local drive it works, but I need to use the SVN server links so that my co-workers can access the same file from their computers.
Here is the file.copy function that is called:
File.Copy(templatePath, notes.ReleaseNotesPath, true);
templatePath is filled out by the user, where I input "serverpath/SoftwareReleaseTool/Trunk/ReleaseNotesTemplates/ReleaseNotes1.docx"
notes.ReleaseNotesPath is defined here:
notes.ReleaseNotesPath = buildFiles[0] + #"\Releases\Notes\VCM-" + model.ReleaseVersion + "-SoftwareReleaseNotes.docx";
the buildFiles[0] part of it is "serverpath/FusionTest/Main"
I should be making new word document but instead I keep getting the same IOException every time.
File.Copy only works in your local file system. You should try something like System.Net.WebClient.DownloadFile
e.g:
using (var client = new WebClient())
{
client.DownloadFile("https://ags-iv-engrpub/svn/SoftwareReleaseTool/Trunk/ReleaseNotesTemplates/ReleaseNotes1.docx", "ReleaseNotes1.docx");
}

I can't not seem to successfully overwrite and some other things

So, basically I've created this program and it's copying the selected file to the the company's named folder in the Roaming AppData folder, which isn't so bad. I mean, the setup now isn't so bad but I would like to have more control over it.
string fullFileName = item.FileName;
string fileNameWithExt = Path.GetFileName(fullFileName);
string destPath = Path.Combine(Application.UserAppDataPath, fileNameWithExt);
File.Copy(item.FileName, destPath);
At the beginning of the program it checks to see if the custom AppData folder is there.
public void checkADfolder()
{
string folder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string specificFolder = Path.Combine(folder, ".program");
if (!Directory.Exists(specificFolder))
Directory.CreateDirectory(specificFolder);
}
I want the files to go to the AppData folder .program instead of the folder with the Application company name.
Also, I am running into an issue with this. When a user selects a file, and then closes the program and opens the program again and happens to select the same file, it gives an error because the file already exists. I need to have it overwrite all other files when the same file is selected.
Screw it, I'll also ask this to why I am here.
I need the user selected file to replace another file in the AppData folder and rename the user selected file.
Basically. User selects file. File name is "user.txt". Now it's in Roaming > .program > user.txt
I need that file to replace a file let's say it's called "guest.txt". It's in Roaming > .user > guest.txt
I need to copy and rename "user.txt" to "guest.txt" then replace "guest.txt" in the .user folder.
I hope that explains everything well enough.
I figured I would put everything into one post instead of making multiple.
I've searched but can not seem to find any answers :/
To overwrite the file you simply need to use the method here:
File.Copy Method (String, String, Boolean);
To overwrite your other file, simply call the function again like so:
File.Copy(#".\Roaming\program\user.txt", #".\Roaming\user\guest.txt", true);

Saving the opened file in particular folder

I have a dropdownlist and a textbox. When i write some name and select some options in dropdownlist like word or excel or powerpoint, that particular file opens as an attachment and i should save it in "data" folder which is already present in the solution explorer. My code is like this
string file = TextBox1.Text;
if (dd1.SelectedIndex == 1)
{
Response.ContentType = "application/word";
Response.AddHeader("content-disposition", "attachment;filename =" + file + ".docx");
}
How can I store this file in "data" folder?
The simple answer is "you cannot". Saving file is taking place on the client side. Your web application knows nothing about the client machine (not even whether it's a real browser or another script) and has no control over the client. The end user will have to manually select data folder to save the file to.

Is saving to database just to get an ID a bad hack?

I hope the title is not too confusing. I am trying to make folders with linq-to-sql objects' IDs. Actually I have to create folders before I should save them. I will use them to keep user uploaded files. As you can see I have to create the folder with the FileID before I can save it there. So I just save a record which will be edited or maybe deleted
File newFile = new File();
...//add some values to fields so they don't throw rule violations
db.AddFile(newFile);
db.Save();
System.IO.Directory.CreateDirectory("..Uploads/"+newFile.FileId.ToString());
After that I will have to edit some fields and save again. Of course user might stop upload and I would have to delete it. I know I can write a stored procedure to get the next available FileID but some other upload happening at the same time would get the same number. So they would write in same directory which is a thing I don't want. Should I go on with this, would there be some problems? Can you think of a better way?
Well.. one thing you could do is generate a GUID, and use that for your folder name instead
string uniqueDirectory = System.Guid.NewGuid().ToString("N");
System.IO.Directory.CreateDirectory("..Uploads/"+uniqueDirectory );
//handle upload, save file, errors, etc..
...
//now that the file is uploaded save to the database
File newFile = new File();
newFile.FolderName=uniqueDirectory;
db.AddFile(newFile);
db.Save();

FileUpload - Verifying that an actual file was uploaded

I have a FileUpload control (FileUpload1) on my web form, as well as a "Sumbit" button, a label, and a hidden field that contains a UserID. I have the following code in the button's click event:
string path = Server.MapPath("~/userfiles/");
if (FileUpload.HasFile)
{
try
{
FileUpload1.SaveAs(path + UserID.Value + "/image.jpg");
}
catch
{
Label1.Text = "* unable to upload file";
Label1.Visible = true;
}
}
It works great if I upload an actual file. However, if I type a non-existent filename (for example, "c:\a.jpg", which does not exist on my computer) into the FileUpload's textbox, and click the Sumbit button, HasFile still returns true. Furthermore, SaveAs() does not throw any exceptions, and it is a void function that returns no value indicating success or failure. How do I tell whether a file was actually uploaded?
Just check to see if it exists.
if(File.Exists(myFile)){
//it was uploaded.
}
You could check FileUpload.PostedFile.ContentLength property
You could check if the file exists using File.Exists before calling SaveAs.
Hmmm....
Not sure I understand. First, in your code, FileUpload.HasFile won't compile. If should be FileUpload1.HasFile.
When I correct this, and run your code, this line returns false if the file does not exist...
You can check if file exists after uploading using File.Exists(path); The file object is part of System.IO.
This is not about your actual question, but you should validate any user input, especially if you want users to upload files to a virtual folder on your webserver. You should at least check whether the content type of the file is the one you expect, or - even better, filter (resize) the image using the classes available in the .NET framework.
If you don't do so users may share arbitrary content via your site or place malicious files (e.g. images containing script which might get executed by certain web browsers) on your server.
With additional validation you will also be able to validate if there has actually been content sent.
AND: A really severe vulnerability opens up when you build the save path by concatenating input from a form field (I assume UserID.Value is the POST parameter you mention?). This allows users to decide where to store the content on your server, and, even worse, be able to overwrite existing files!!!

Categories