I'm creating a richtextbox editor and need to put a save function as well as a save as. I can easily do a save as function by using the savefiledialog but im not sure how to save without this. Can anyone help?
Create a field somewhere, say string filename. Set it to null initially.
When a document is opened, store the file name in a filename.
When a document is saved through Save As, also store this file name in filename.
When Save is invoked, check the value of filename. If it is null, invoke Save As instead. If it is not null, save to the file name specified in filename.
The way this usually works is to keep track of the file name the user either opened or saved as.
Then, when they use the Save function, simply save to the file name that was previously specified. If no file has been specified, then show the Save As.
Isn't "Save" simply the following (in pseudocode)?
Save() =
WriteTo(oldfilename)
SaveAs() =
stream = OpenDialog()
oldfilename = stream.filename
Save()
Related
I want to filling windows form data to excel. the end of code I give validation so if the filename exist on specific location it would not save it again
string savingNewForm = "C:\\temp\\" + temp;
if (File.Exists(savingNewForm))
{
MessageBox.Show("File already exist!");
oBook.Close();
oApp.Quit();
}
else
{
oBook.SaveAs(savingNewForm);
oBook.Close();
oApp.Quit();
MessageBox.Show("Your file saved");
}
but when user save the same filename it give error.
I think the main problem is on if (File.Exists(savingNewForm)) cause it's not checking if the filename exist or not, instead it goes to else and give a popup excel asking if I want to replace or not.
What is the value of temp? There could be a problem if the filename contains invalid characters or is too long, etc.
From MSDN:
The Exists method should not be used for path validation, this method
merely checks if the file specified in path exists. Passing an invalid
path to Exists returns false.
If path describes a directory, this method returns false.
The Exists method returns false if any error occurs while trying to determine if the specified file exists.
If the directory doesn't exist or if the user does not have permission to read the file (maybe it's locked) then File.Exists() will return false.
If it's an issue with the existence of the file, see Softerware's answer. If you want Excel to not ask the user to overwrite, try:
oApp.DisplayAlerts = false;
Although I haven't worked with your excel library, suggest you to try workaround:
save into another file;
remove target;
move saved file to target filename.
Error on file removing will be more informative anycase.
I am developing an app right now that reads in data from a windows from and generates an XML file based on the input.
I am tasked with creating a new file each time the form is updated (User presses "Submit"). (so far so good)
Here is the catch: The file has to be named after a prominent field input. (If the user types '993388CX' in the text box, the app would rename the pending file 993388CX.xml).
I understand how to actually rename a file in C#, but not how to rename it based on a form's input. Do any classes/methods exist that will dynamically rename the file based on the form input?
Code:
//Reads info1 from user input on the app UI and generates XML statement
XTemp = XDoc.CreateElement("New_Info");
XTemp.InnerText = info1.Text;
Xsource.AppendChild(XTemp);
XDoc.Save(#"C:\oldfile.xml");
I need the new file to be renamed after the string in info1.Text
If the user input was "John5", the file needs renamed to john5.xml
Thank you
Either directly save it with the correct name:
XDoc.Save(String.Format("C:\\{0}.xml",info1.Text));
OR
Rename it afterwards
File.Move("c:\\oldfile.xml", String.Format("C:\\{0}.xml",info1.Text));
XDoc.Save(#"C:\" + info1.Text + ".xml");
File.Move should do what you want.
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();
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!!!
I am importing a source file and processing it and then after that I have to save it in a new location. I have created the syntax for importing file, tell me the syntax to save it to a new location. One is when I am calling the constructor to give the path of import file, then I can also give the path for the output location. But don't know how to implement it. Please tell.
You can use a SaveFileDialog pretty much like this:
using ( var dlg = new SaveFileDialog() )
{
if ( dlg.ShowDialog() == DialogResult.OK )
{
//SAVE THE OUTPUT
//DEPENDING ON THE FORMAT, YOU MAY WANT TO USE
//File.WriteAllBytes(dlg.FileName, yourBytes);
//File.WriteAllText(dlg.FileName, yourText);
//File.WriteAllLines(dlg.FileName, yourStringArr);
//OR ANY OTHER CODE YOU WANT TO USE TO PERSIST YOUR DATA
}
//else the user clicked Cancel
}
Also, you can set a default extension, a default path and more. Look up SaveFileDialog's information on MSDN
As your importing the file you could use the StreamWriter base class to write it to a file that the end user designates in a either a text box or a file upload box.