Coding Platform: ASP.NET 4.0 C#
Consider the following scenario.
I am uploading a file named "StackOverflow.doc" to the folder Documents using asp:FileUpload.
But the folder documents already have a file named "StackOverflow.doc".
In this situation I would like to rename my file as StackOverflow(1).doc.
I do know how to make file names unique using GUID or by assigning temporary names.
But what I need is a windows explorer like solution. Which is the best way to approach it?
P.S: The solution should be redundant. That is, if there are files named StackOverflow.doc and StackOverflow(1).doc, my renamed file should be StackOverflow(2).doc
Here is one approach to getting a file name as you are asking (the file path logic not included for brevity):
string fileName = downloadFileName;
string fileExt = downloadFileExtention;
string fullFileName = string.Format("{0}.{1}", fileName, fileExt);
int counter = 0;
while(File.Exists(fullFileName))
{
counter++;
fullFileName = string.Format("{0}({1}).{2}", fileName, counter, fileExt);
}
// Write the file to fullFileName
Related
I'm trying to move a file from the desktop to a directory called "Textfiles" but every time I try to it gives me this error.
Additional information: The target file "C:\Users\Developer\Documents\Textfiles" is a directory, not a file.
Now I know that using
File.Copy(fileName, targetPath);
Would be wrong and that's what I am using right now, It takes two parameters, the first being the file yopu want to copy and the second one being the file it's replacing? Correct me if i am wrong on the second parameter.
Anyways, I tried System.IO.Directory.Move(fileName, destFile); aswell but that pretty much gave me the same error.
The two parameters are very simple, just two string that consists of paths.
string fileName = filePath.ToString();
string targetPath = #"C:\Users\Developer\Documents\Textfiles";
What would be the correct way to transfer fileName to targetPath ?
You need to specify the destination filename.
string fileOnly = System.IO.Path.GetFileName(fileName);
string targetPath = System.IO.Path.Combine(#"C:\Users\Developer\Documents\Textfiles", fileOnly);
System.IO.File.Move(fileName, targetPath);
See https://msdn.microsoft.com/en-us/library/c6cfw35a(v=vs.110).aspx
for documentation:
destFileName
Type: System.String
The name of the destination file. This cannot be a directory or an existing file.
You have to add the new file name to the destination directory.
You can get the file name with:
result = Path.GetFileName(fileName);
thus in your case:
string targetPath = #"C:\Users\Developer\Documents\Textfiles\" + Path.GetFileName(fileName);
I have been using a LocalDB.mdf file to build my application, but now need to use it in production and create an installable application.
After research, it seems the best place to store such a file is in the /Appdata/Local/ folder.
I intend to create a new LocalDB.mdf file in there if it doesnt already exist, or has been deleted.
I have a pre-made LocalDB.mdf file in my App Resources, which I wanted to copy into this /Appdata/Local/ folder on first run, but I am seeing an Access is denied error.
I can create a blank file ok to that folder.
Here is the code:
string appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
string dvAppDataFolder = appDataFolder + #"\MyApp";
AppDomain.CurrentDomain.SetData("DataDirectory", dvAppDataFolder);
if (!Directory.Exists(dvAppDataFolder))
Directory.CreateDirectory(dvAppDataFolder);
if (!File.Exists(dvAppDataFolder + "LocalDB.mdf"))
{
File.WriteAllBytes(dvAppDataFolder, LokiServer.Properties.Resources.newDB);
}
In addition, Am I going about this the right way?
This line
if (!File.Exists(dvAppDataFolder + "LocalDB.mdf"))
is probably wrong. Missing the backslash, better to use Path.Combine instead of a string concatenation.
Finally, you want to write to a file not to a folder
string fileName = Path.Combine(dvAppDataFolder,"LocalDB.mdf");
if (!File.Exists(fileName))
{
File.WriteAllBytes(fileName, LokiServer.Properties.Resources.newDB);
}
Are you doing it right? It depends. If your app data should be kept separated for each user of your target machine then you are right, but if you want your database to be available to all users of that machine then use
string appDataFolder = Environment.GetFolderPath
(Environment.SpecialFolder.CommonApplicationData);
I'm using C# windows application .
I want to save files in my local system.
I used Open File dialog to attach the files.
Here the text inside the file is copying,I want the file itself to get copied with a new name.But what I am really looking for is , it should just save the file automatically and not show the SaveDialog Box?
How it can be done in windows application.Can anybody help me please?
The code is shown below:
private string GetFileName()
{
OpenFileDialog op1 = new OpenFileDialog();
DialogResult result = op1.ShowDialog();
if (result == DialogResult.OK) // Test result.
{
txtEn.Text = op1.FileName;
FileName = op1.FileName;
//MessageBox.Show(FileName);
File.Copy(op1.FileName, #"D:\Backup\");
}
return FileName;
}
SQL Server 2012 seems unrelated to your question. Provided that you have proper access rights to the target directory, then in order to automate the procedure (as per your question) you don't need to use the OpenFileDialog; just a single line should suffice the goal:
//Overwriting a file of the same name is not allowed
File.Copy(FileName, #"D:\Backup\" + FileName)
or
//Overwriting a file of the same name is allowed
File.Copy(FileName, #"D:\Backup\" + FileName, true)
You can also apply some additional logic pertinent to backup file naming (upon necessity).
Hope this may help. Best regards,
Are you trying to copy a file from some x location on your file system to y location (in your case D:\Backup folder) in the file system? If that is the requirement here, I see that you are using the FileName property of OpenFileDialog which gets the File path. This you are appending to D:\Backup. You should instead use the Path.GetFileName property to first extract the file name with extension and then append it to the new folder path
File.Copy(fileName, #"D:\Backup\" + Path.GetFileName(fileName));
i am writing a console app in c# to check if file 'id' in sql server table matches filename of file on local directory...i know how to use filename to check a location(all this does is check file exists in local directory)...
for example if there was an entry in a sql table of value '925677bb-cabb-4ff1-8c90-3e130a77b366'...i would want to perform check on location (c:\...) where any files with that filename would exist, ie '925677bb-cabb-4ff1-8c90-3e130a77b366.jpg'
what would be the best way to do this?
You could use the File.Exists function:
string id = ... go and fetch from your db
string filename = Path.ChangeExtension(Path.Combine(#"c:\somefolder", id), ".jpg");
if (File.Exists(filename))
{
// the file c:\somefolder\925677bb-cabb-4ff1-8c90-3e130a77b366.jpg exists
}
Make use of Directory.GetFiles(), like this
string []files = Directory.GetFiles(#"C:\", "925677bb-cabb-4ff1-8c90-3e130a77b366*.jpg")
in this way you will get all files that starts with specified string in C:\ directory
So if the array files is empty, there is no any file like that, otherwise, there is at least one.
I have got this read file code from microsoft
#"C:\Users\computing\Documents\mikec\assignment2\task_2.txt"
That works fine when im working on it, but when i am to hand in this assignment my lecturer isn't going to have the same directory as me.
So i was wondering if there is a way to read it from just the file the program is held in?.
I was thinking i could add it as a resource but im not sure if that is the correct way for the assignment it is meant to allow in any file.
Thanks
You can skip the path - this will read file from the working directory of the program.
Just #"task_2.txt" will do.
UPDATE: Please note that method won't work in some circumstances. If your lecturer uses some automated runner (script, application whatsoever) to verify your app then #ken2k's solution will be much more robust.
If you want to read a file from the directory the program is in, then use
using System.IO;
...
string myFileName = "file.txt";
string myFilePath = Path.Combine(Application.StartupPath, myFileName);
EDIT:
More generic solution for non-winforms applications:
string myFilePath = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), myFileName);
If it is a command line application, you should take the file name as a command line argument instead of using a fixed path. Something along the lines of;
public static void Main(string[] args)
{
if (args == null || args.Length != 1)
{
Console.WriteLine("Parameters are not ok, usage: ...");
return;
}
string filename = args[0];
...
...should let you get the filename from the command.
You could use the GetFolderPath method to get the documents folder of the current user:
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
and to exemplify:
string myDocuments = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string file = Path.Combine(myDocuments, #"mikec\assignment2\task_2.txt");
// TODO: do something with the file like reading it for example
string contents = File.ReadAllText(file);
Use the relative path.
you can put your file inside the folder where your application resides.
you can use Directory.GetCurrentDirectory().ToString() method to get the current folder of the application in. if you put your files inside a sub folder you can use
Directory.GetCurrentDirectory().ToString() + "\subfolderName\"
File.OpenRead(Directory.GetCurrentDirectory().ToString() + "\fileName.extension")
StreamReader file = new StreamReader(File.OpenRead(Directory.GetCurrentDirectory().ToString() + ""));
string fileTexts = file.ReadToEnd();