简体   繁体   English

C#.NET file.copy目录路径

[英]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). 我不是母语人士,我从今天开始几乎没有任何编程知识就开始学习C#,我想编写Windows窗体程序,它将包含在程序中的文件(图形资产)复制到另一个程序目录中的某些文件夹中(更准确地说,我想通过单击按钮来修改图形资产,然后能够将其更改回。 I did my research and I know that I should use File.Copy method I just have one question about code I found: 我做了研究,我知道我应该使用File.Copy方法,但我对所发现的代码只有一个疑问:

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/"? 我可以这样定义sourcePath和targetPath吗:例如“ ./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 AppDomain.CurrentDomain.BaseDirectory

Remeber to verify that the directory you're reffering to exists or otherwise you might get a DirectoryNotFoundException 请记住您要引用的目录是否存在,否则可能会收到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. 您可以提供I / O操作的相对路径,默认路径是Environment.CurrentDirectoy值,并且大多数情况下这将是Windows Forms可执行文件的工作目录。

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 . 请注意,您不需要路径中的./起点, File.Copy("FileA.txt", "FileA_1.txt")会在Environment.CurrentDirectory查找这些位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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