c# - 如何将资源文件夹分配给字符串

c# - How to assign resources folder to a string

我目前正在使用这个,

string finename = "text.txt"; //setting file name

//setting locations
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string filepath = @"C:\User\Users\Documents\Files\Apple"; // <--- need to use Resources folder in the project folder here


//filename and location combining to be copied
string source = Path.Combine(filepath,filename);
string destination = Path.Combine(path,filename);

if (something=1)
{ 
    File.Copy(source,destination, true); //copying
}

我已经将所有文件添加到资源中,现在我需要在此处引用资源文件夹而不是 "filepath", 有没有办法将资源文件夹(及其内容)分配给一个字符串,这样我就可以简单地更改位置?然后我也可以在其他 PC 上使用此代码。

编辑 -

假设我在资源文件夹中有 orange、mango 和 apple 文件夹,这 3 个文件夹中的每一个都包含一个名为 "text.txt" 的文本文件。

而且我需要根据要求从每个水果文件夹中复制这些文本文件之一并将其粘贴到桌面上。

现在我需要在 3 个不同的字符串上存储 "Resources\apple" 、 "Resources\orange" 和 "Resources\mango" 的位置,这样我就可以简单地在 "string source = Path.Combine(filepath,filename)" 部分调用它们而不是older "filepath" 将这些文本文件从 resources 文件夹中的任何 fruit 文件夹复制到桌面。

谢谢。

Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

您在这里所做的是检索您的桌面路径并将您的 .txt 文件从您的文件路径复制到那里。 您没有将文件复制到您的项目 "Resources" 文件夹中。

如果您的文件如@Prasad telkikar 所说,使用以下代码,您将获得 "Resource" 文件夹的路径,并能够访问其中的所有内容。

string path = Path.Combine(Environment.CurrentDirectory, "Resources");
  1. 获取src or root文件夹路径。
  2. 将根文件夹路径与资源文件夹路径合并。
  3. 将结果(root\resources) 与您的文件名合并

在这里,您将获得文件的确切路径,现在您可以将其复制到目的地。

这是实现:此代码在我的机器上 运行。

/// <summary>
/// Here you just need to send fruit name
/// </summary>
/// <param name="fruitName">Name of fruit</param>
public void CopyFile(string fruitName)
{
    string filename = "text.txt"; //setting file name
    string resouceFolderName = Path.Combine("Resources", fruitName);
    //Destination Path
    string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
    //CurrentDirectory return src\Bin\Debug so extracting src root folder path
    string parentFolderPath = Directory.GetParent(Directory.GetParent(Environment.CurrentDirectory).FullName).FullName;
    //combining parent folder path with resource folder name
    string folderPath = Path.Combine(parentFolderPath, resouceFolderName); // <--- need to use Resources folder in the project folder here

    //Checking if exist or not
    if (!Directory.Exists(folderPath) || !Directory.Exists(path))
    {
        Console.WriteLine("Error");
        return;
    }

    //filename and location combining to be copied
    string source = Path.Combine(folderPath, filename);
    string destination = Path.Combine(path, filename);

    if (true)
    {
        File.Copy(source, destination, true); //copying
    }
}

注意:这里我使用了test.txtResources字符串作为不断考虑他们不会改变