[英]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");
src or root
文件夹路径。 在这里,您将获得文件的确切路径,现在可以将其复制到目标位置。
这是实现:此代码在我的计算机上运行。
/// <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.txt和Resources字符串用作常量,因为它们不会更改
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.