簡體   English   中英

CodeGo.net>如何分配資源文件夾的字符串

[英]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”的文本文件。

我需要根據需要從每個水果文件夾復制這些文本文件之一,並將其​​粘貼到桌面上。

現在,我需要將“ Resources \\ apple”,“ Resources \\ orange”和“ Resources \\ mango”的位置存儲在3個不同的字符串上,以便我可以在“字符串source = Path.Combine(filepath,filename)”中簡單地調用它們部分而不是較舊的“文件路徑”將這些文本文件從資源文件夾內的任何水果文件夾復制到桌面。

謝謝。

Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

您在這里所做的是獲取桌面的路徑,並將.txt文件從文件路徑復制到該路徑。 您沒有將文件復制到項目的“資源”文件夾中。

如果您的文件如@Prasad telkikar所說的那樣存在,則使用以下代碼,您將具有您“ Resource”文件夾的路徑,並能夠訪問其中的所有內容。

string path = Path.Combine(Environment.CurrentDirectory, "Resources");
  1. 獲取src or root文件夾路徑。
  2. 將根文件夾路徑與資源文件夾路徑合並。
  3. 將結果(根\\資源)與您的文件名合並

在這里,您將獲得文件的確切路徑,現在可以將其復制到目標位置。

這是實現:此代碼在我的計算機上運行。

/// <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字符串用作常量,因為它們不會更改

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM