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

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();

Related

Increment Counter

In my application there is a option for where user creates a simple txt file containing some data. I would like to name the file in sequential order like ST1, ST2.... This sequence will be remain same for all users. if user1 creates a file system should name the file ST100 and then if user2 creates a file then system should name the file ST101.
I cant use the application scope as it is ready only and cant be changed at run time where as the user scope will only impact individual user not across the whole application.
I was wondering is there any other solution to achieve this apart from using database table and tacking sequence.
Thanks
You could use a loop and File.Exists:
var dir = #"C:\SampleFolder";
int number = 100; // you want to start at 100
string fileName = String.Format("ST{0}.txt", number.ToString("D3"));
while(File.Exists(Path.Combine(dir, fileName)))
fileName = String.Format("ST{0}.txt", (++number).ToString("D3"));
Finally you will have a new file-name and you get the correct path:
string path = Path.Combine(dir, fileName);
if your application is always on, you can use a global variable for the entire system with the numeric value of the next entry.
if not, you can use a text file as a database with the current number of the file; The problem with this solution is the synchronization, if two users doing the same operation at the same time can give you problems, so it is best to use a database.
I hope it helps you

How to backup a complete file?

What is the most efficient way to make a backup of a file when it's being opened into the program, so that when the user changes and saves it, there is always a way to go back?
Example:
private void open_click(object sender, EventArgs e)
{
ofd.DefaultExt = "";
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
fileIn = ofd.FileName;
fileOut = Path.GetTempFileName();
string encoded = File.ReadAllText(fileIn);
etc. etc. etc
}
The file that gets loaded into the program needs to get backed up as backup_01 and put in the same folder as the original file. When backup_01 exists, backup as backup_02, and so on).
Examples are more than welcome!
I would generally create a copy of the file itself, place it in a "backup" folder, and apply some naming scheme to it to indicate its age.
Eg: folder/originalFile.xyz ==> folder/backup/originalFile_2013-04-14-12-48.bak
Update/afterthought: I think the efficiency of this will depend on the OS performing the Copy-operation, but it should in general not be too bad. Unless you have good reason to do so, I would avoid trying to add extra logic to do it more efficiently.
Update in response to comment:
I won't provide a detailed implementation here, but I'll try to point you in the right direction: Check out System.IO.File, specifically the methods Copy and Exists. (This list of other common IO-taks may also be useful)
With these, you should be able to check if a file exists (eg. if you already have "backup_1.xyz" in your backup-folder), and based on that, generate a new name for your next backup file.
Create a loop that replaces 1 with increasing numbers until you find a "free" filename, and then copy the original file to a new file with that name.
Good luck! :)

Deleting an unlocked file in C#

In a C# program, I am creating files. I want to delete one file using this command:-
File.Delete(killFile);
The killFile has a value = "C:\Documents and Settings\MehdiAnis\My Documents\outfile_0020.csv"
The killFile is an existing file.
After I run Delete command, file is still in the Directory. Right after delete I added FileInfo code to check if the file exists,
FileInfo fi = new FileInfo(killFile);
Now, fi.Exists shows false
I am not sure what's wrong, can it be permission issue? I just wrote the file in my own folder, why can't I delete it? Once the file is created I am not opening it or doing anything with it, so it should not be locked.
What could be wrong and where else should I be looking?
Per the screenshot you posted at http://i548.photobucket.com/albums/ii341/MehdiAnis/cprob.jpg
In your screen shot, the explorer window is showing a file with name eding in "_0020.csv" . You are passing in a filename ending with "_20.csv", according to the debugger window. You are calling File.Delete with the name of a file that doesn't actually exist, and so no file is deleted.
You will want to format your "killFile" variable with 0 padding. I assume you are adding some counter to it like killfile = killFile + i.ToString(). Try killfile = killFile + i.ToString("0000")
According to MSDN, "If the file to be deleted does not exist, no exception is thrown."
You may want to check for existence of the file to be deleted using File.Exists before trying to delete it. I think your problem is the file you are expecting to delete isn't the file that you see in the folder.

How to Save not Save As

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()

How to save the file in a path chosen by the user

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.

Categories