简体   繁体   中英

C#.NET file.copy directory path

Couple prerequisites to this question first. I'm not a native speaker, I started to learn C# today with almost no prior programming knowledge, I want to write windows form program that will copy files (graphics assets) that I include with the program to certain folders in another programs directory (to be more precise I w want to modify graphic assets with a click of a button and then be able to change those back). I did my research and I know that I should use File.Copy method I just have one question about code I found:

static void Main()
{
    string fileName = "test.txt";
    **string sourcePath = @"C:\Users\Public\TestFolder";
    string targetPath =  @"C:\Users\Public\TestFolder\SubDir";**

    // Use Path class to manipulate file and directory paths.
    string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
    string destFile = System.IO.Path.Combine(targetPath, fileName);

I know this is not complete code but this is the part I want to ask my question about. Can I define sourcePath and targetPath like this for example: "./folder/folder2/"? Basically I want my program to assume that it's in "correct directory" of another software and I don't want to specify entire path to that directory. In other words is my program aware of which directory it's in currently and if not how can I make it aware? I hope I phrased that correctly. Thank you for your help.

To be sure that you're referring to the application's path you can use this:

string exePath = System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetEntryAssembly().Location);

Or AppDomain.CurrentDomain.BaseDirectory

Remeber to verify that the directory you're reffering to exists or otherwise you might get a DirectoryNotFoundException

You can provide a relative path to I/O operations, and the default path is the Environment.CurrentDirectoy value, and mostly this will be the directory where your Windows Forms executable is working from.

Note that you don't need the ./ starting point in your path, File.Copy("FileA.txt", "FileA_1.txt") will look for these locations in Environment.CurrentDirectory .

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