简体   繁体   中英

How can I run c# code from a button click?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM