How would I search for a file (in the current directory the exe is running in) and if it is not found, it will download it?
I already know how to do the downloading part, WebClient.DownloadFile("link.com","link.exe");
TL;DR:
How would I search for a file in the directory (link.exe) and if it is not there, download it?
If you already have the full path where the file should be located, you can simply call System.IO.File.Exists(thePath), which will return either true or false.
Note that thePath must be the full path to the file, not to the folder.
Or do you need something else?
You want to firstly find out which directory you are in. Then you want check whether the file exsist or not.
string file_location = Environment.CurrentDirectory + "link.exe";
if (File.Exists(file_location) == false)
{
WebClient.DownloadFile("link.com", "link.exe");
}
Environment.CurrentDirectory:
https://msdn.microsoft.com/en-us/library/system.environment.currentdirectory(v=vs.110).aspx
File.Exists:
https://msdn.microsoft.com/en-us/library/system.io.file.exists(v=vs.110).aspx
Related
File.Copy(#"my program\\subfolder\\what i want to copy.txt", "C:\\Targetlocation");
How can i copy a text file from one folder to another using relative path.
To execute the File.Copy the source and destination will be a valid file path. in your case the destination is a folder not File. in this case you may get some exception like
Could not find a part of the path 'F:\New folder'
While executing the application, the current directory will be the bin folder. you need to specify the relative path from there. Let my program/subfolder be the folders in your solution, so the code for this will be like this:
string sourcePath = "../../my program/subfolder/what i want to copy.txt";
string destinationPath = #"C:\Targetlocation\copyFile.txt"
File.Copy(sourcePath, destinationPath );
Where ../ will help you to move one step back from the current directory. One more thing you have to care is the third optional parameter in the File.Copy method. By passing true for this parameter will help you to overwrite the contents of the existing file.Also make sure that the folder C:\Targetlocation is existing, as this will not create the folder for you.
File.Copy(#"subfolder\\what i want to copy.txt", "C:\\Targetlocation\\TargetFilePath.txt");
The sourceFileName and destFileName parameters can specify relative or
absolute path information. Relative path information is interpreted as
relative to the current working directory. This method does not
support wildcard characters in the parameters.
File.Copy on MSDN
Make sure your target directory exists. You can use Directory.CreateDirectory
Directory.CreateDirectory("C:\\Targetlocation");
With Directory.CreateDirectory(), you don't have to check if the directory exists. From documentation:
Any and all directories specified in path are created, unless they
already exist or unless some part of path is invalid. The path
parameter specifies a directory path, not a file path. If the
directory already exists, this method does nothing.
// Remove path from the file name.
string fName = f.Substring(sourceDir.Length + 1);
try
{
// Will not overwrite if the destination file already exists.
File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName));
}
You can provide the relative path from your current working directory which can be checked via Environment.CurrentDirectoy.
For example if your current working directory is D:\App, your source file location is D:\App\Res\Source.txt and your target location is D:\App\Res\Test\target.txt then your code snippet will be -
File.Copy(Res\\Source.txt, Res\\Test\\target.txt);
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.
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);
I want to save image into a folder and the path of the folder to the database.
I have done this with File.Copy(filepath) command but it is giving me error when a file with the same name already exists there.
Second thing in this command is that I have to provide a filename in it from which it is copying the file. If I am modifying a record and not the image then it is giving error that file source cannot be empty.
I have also tried Picture1.image.save(filename) but I have not found any command to overwrite the existing file.
Please help me by providing a simplest way to do all this.
There's an overload to the File.Copy() method that accepts a bool which will determine whether to overwrite any existing files with the same name.
http://msdn.microsoft.com/en-us/library/9706cfs5.aspx
File.Copy(sourceFileName, destFileName, true) Will force an overwrite of existing file.
Refer MSDN File.Copy
if(File.Exists(destinationFileName))
{
File.Delete(destinationFileName);
}
File.Copy(sourceFileName, destinationFileName);
sourceFileName shoudl be the full path of the source file(including the file name).
destinationFileName should be the fullpath (including the filename) where you want to save the file.
you have to first check whether file exists or not?
using FileInfo,
FileInfo file = new FileInfo(location);
if(file.Exists())
{
File.Delete(location);
File.Copy(srcLocation, location);
}
In this way you can avoid the error.
There is a text file that I have created in my project root folder. Now, I am trying to use Process.Start() method to externally launch that text file.
The problem I have got here is that the file path is incorrect and Process.Start() can't find this text file. My code is as follows:
Process.Start("Textfile.txt");
So how should I correctly reference to that text file? Can I use the relative path instead of the absolute path? Thanks.
Edit:
If I change above code to this, would it work?
string path = Assembly.GetExecutingAssembly().Location;
Process.Start(path + "/ReadMe.txt");
Windows needs to know where to find the file, so you need somehow specify that:
Either using absolute path:
Process.Start("C:\\1.txt");
Or set current directory:
Environment.CurrentDirectory = "C:\\";
Process.Start("1.txt");
Normally CurrentDirectory is set to the location of the executable.
[Edit]
If the file is in the same directory where executable is you can use the code like this:
var directory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
var file = Path.Combine(directory, "1.txt");
Process.Start(file);
The way you are doing this is fine. This will find the text file that is in the same directory as your exe and it will open it with the default application (probably notepad.exe). Here are more examples of how to do this:
http://www.dotnetperls.com/process-start
However, if you want to put a path in, you have to use the full path. You can build the full path while only caring about the relative path using the method listed in this post:
http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/e763ae8c-1284-43fe-9e55-4b36f8780f1c
It would look something like this:
string pathPrefix;
if(System.Diagnostics.Debugger.IsAttached())
{
pathPrefix = System.IO.Path.GetFullPath(Application.StartupPath + "\..\..\resources\");
}
else
{
pathPrefix = Application.StartupPath + "\resources\";
}
Process.Start(pathPrefix + "Textfile.txt");
This is for opening a file in a folder you add to your project called resources. If you want it in your project root, just drop off the resources folder in the above two strings and you will be good to go.
You'll need to know the current directory if you want to use a relative path.
System.Envrionment.CurrentDirectory
You could append that to your path with Path
System.IO.Path.Combine(System.Envrionment.CurrentDirectory, "Textfile.txt")
Try using Application.StartupPath path as default path may point to current directory.
This scenario has been explained on following links..
Environment.CurrentDirectory in C#.NET
http://start-coding.blogspot.com/2008/12/applicationstartuppath.html
On a windows box:
Start notepad with the file's location immediately following it. WIN
process.start("notepad C:\Full\Directory\To\File\FileName.txt");