0

I made a program in C# and was using a hardcoded reference to the Program Files directory whilst making the program. I'd now like to remove the hardcoded reference.

I have been recommended this method from Eric on stackoverflow in a recent topic. However, I wasn't able to understand how to run the code from a button_click:

Eric said:

string programFilesFolder = 
    Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)

Continuing that example you could do something like this

string pathToFile = 
    Path.Combine(programFilesFolder, @"TEST\ok.txt");

if (File.Exists(pathToFile)) 
    File.Delete(pathToFile);

To be 100% honest with you all, I am newish to c# and am still learning...

Can someone please give an example on how to invoke the code above from a button_click? I am going to be doing this to more than one file using the same button.

I did ask this question in a comment on the other thread, but I think they all moved on.

4
  • 1
    Protip: You dont need to check if the file exists before deleting. In fact, if you needed to do so, you will have a possible race condition. Commented Jul 19, 2012 at 5:05
  • True, however after the file is deleted i will copy a file from my install folder to TEST and it will be same file name as ok.txt. I would edit the above however i am quoting someone elses post so.. Commented Jul 19, 2012 at 5:07
  • What is the problem in using the method in button click? why not use Path.Combine(programFilesFolder, @"TEST\ok.txt") where you hard coded the path before? Commented Jul 19, 2012 at 5:08
  • 2
    I'm just a bit confused. If i used Path.Combine(programFilesFolder, @"TEST\ok.txt") then how would it know the programFilesFolder? don't i have to insert all of the above into the C#? Thats what i don't understand. Commented Jul 19, 2012 at 5:10

1 Answer 1

1

Assuming that you want to make a Windows Forms application to do this:

http://msdn.microsoft.com/en-us/library/z9w2f38k(v=vs.90).aspx

That will show an example of how to do a Windows Forms example where you can drag a button onto a canvas and then have a click action on the button.

In the example it says to put

MessageBox.Show ("Hello, World!")

but you could put the code to delete the file there instead and it will delete whatever you want to delete on the click of the button.

string programFilesFolder = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)
string pathToFile = Path.Combine(programFilesFolder, @"TEST\ok.txt");
File.Delete(pathToFile);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.