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

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

Related

avoid overwriting of file and content with each run or request with executable directory

Hello I’m trying to create directory folder with text document for my windows form application executable. Now I must make it available locally for other users.
I'm doing it this way:
string dir = "%ProgramData%\\MyAppName\\doc.txt";
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(Path.GetDirectoryName(dir));
var stream = File.CreateText(dir);
stream.Close();
}
and here is my access path from executable directory inside the code:
const string mypath = (#"%ProgramData%\MyAppName\doc.txt");
On the one stage of implementation I have also separate creation of document, but I almost sure that has no connection with problem, because creates it once and never overwrites if file exist, keeps content of text document with each new run of program, adding of data or request to it. Only if I delete it by hand, in this case creates new one:
if (File.Exists(mypath))
wordsTyped.AddRange(File.ReadAllLines(mypath));
and works perfect with local path to debug folder like this:
const string tetdb = ("doc.txt");
So code for executable must work same way, if directory, folder, file with content exist don't do nothing with it. But with code above, it rewrites everything with every request to it, not only with new run of program, with folder, text document and content inside.
but must be as follows: if folder is created once, if directory, file, document exist, no netter with code of executable, or with press enter, or it was already there. keep content inside the text document with every start of program or request to it of adding to it.
I've tried create only folder to executable path, to create text document separately as it shown above, but I got same result. So how to avoid this problem, what I'm doing wrong?
The test for !Directory.Exists is the cause of your problem.
You pass a filename to the method, thus the method returns false (a directory with that name doesn't exist).
This means that you always enter the if and calling File.Create over an existing file overwrite the content of the file
string file = "%ProgramData%\\MyAppName\\doc.txt";
if (!Directory.Exists(Path.GetDirectoryName(file)))
{
....
}

Search for file, if not there then download

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

Detect when OpenFileDialog returns a downloaded URL/URI

I'm using OpenFileDialog (.Net Framework 4, Windows 10) and I've noticed that it will allow the user to specify a URL as the file name (e.g., http://somewebsite/picture.jpg). This is very useful for my application, so I don't intend to disable it. The way it works is downloading the file into the user's temp directory and returning the temporary file name in the dialog's Filename property. This is nice, except for the fact that the user starts to build up garbage in his/her temp directory.
I would like to tell when a file was downloaded by the OpenFileDialog class (as opposed to a previously existing file), so I can clean up by deleting the file after use. I could check if the file's directory is the temp directory, but that's not very good since the user might have downloaded the file him/herself.
I've tried intercepting the FileOK event and inspect the Filename property to see if it is an HTTP/FTP URI, but despite what the documentation says ("Occurs when the user selects a file name by either clicking the Open button of the OpenFileDialog") it is fired after the file is downloaded, so I don't get access to the URL: the Filename property already has the temporary file name.
EDIT: This is an example of what I'like to do:
Dim dlgOpenFile As New System.Windows.Forms.OpenFileDialog
If dlgOpenFile.ShowDialog(Me) <> Windows.Forms.DialogResult.OK Then Return
''//do some stuff with dlgOpenFile.Filename
If dlgOpenFile.WasAWebResource Then
Dim finfo = New IO.FileInfo(dlgOpenFile.Filename)
finfo.Delete()
End If
In this example, I've imagined a property to dlgOpenFile "WasAWebResource" that would tell me if the file was downloaded or originally local. If it's the first case, I'll delete it.
There's no obvious way to do this, but as a workaround, how about checking where the file lives? It looks like by default this dialog downloads files to the users Temporary Internet Files directory, so you could introduce some code that looks something like this:
FileDialog dialog = new OpenFileDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
string temporaryInternetFilesDir = Environment.GetFolderPath(System.Environment.SpecialFolder.InternetCache);
if (!string.IsNullOrEmpty(temporaryInternetFilesDir) &&
dialog.FileName.StartsWith(temporaryInternetFilesDir, StringComparison.InvariantCultureIgnoreCase))
{
// the file is in the Temporary Internet Files directory, very good chance it has been downloaded...
}
}

Access to Resources

I've C# project and it has Resources folder. This folder has some of txt files. This files have various file names.
I'm taking file names from any source as string variable. For example I have fileName string variable and test.txt file in Resources folder:
string fileName = "test.txt";
When I want to access this file as like below, I can:
WpfApplication.Properties.test.txt;
But, When I want to access it by this code, I can't.
WpfApplication.Properties.fileName;
I want to use fileName string variable and access this text file.
What can I do to access it?
Thanks in advance.
Edit :
I change form of this question:
I've string variable assigned any text file name. For example; I have a.txt, b.txt, c.txt, d.txt, etc.. I'm taking this file name as string variable (fileName) via some loops. So, I took "c.txt" string. And, I can access this file by code in below:
textName = "c.txt";
fileName = "../../Resources\\" + textName;
However, when I build this project as Setup Project and install .exe file to any PC, there is no "Resources" folder in application's folder. So,
../../Resources\
is unavailable.
How can I access Resources folder from exe file's folder?
You need to add a Resource File to your project wich has the extension .resx/.aspx.resx. You will then be able to double click on this file and edit the required resources/resource strings. To do this right click on Project node in Solution Explorer > Add > New Item > Resource File. Let us assume you have added a file called ResourceStrings.resx to the Properties folder and added a resource string with key name MyResourceString, to access these strings you would do
string s = Properties.ResourceStrings.MyResourceString;
I hope this helps.
I would strongly recommend you taking a look at: http://msdn.microsoft.com/en-us/library/aa970494.aspx
If your text files have build action set as Resource you can locate them in code like:
(assuming the file name is fileName and its located in Resources folder)
Uri uri = new Uri(string.Format("Resources/{0}", fileName), UriKind.Relative);
System.Windows.Resources.StreamResourceInfo info = Application.GetResourceStream(uri);
Then you can access info.Stream to get access to your file.

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.

Categories