C# 以映射名部分已知的目录为目标

C# Targeting a directory of which a mapname is partially known

我正在尝试使用 gmail 中的 smtp 发送文件,但我偶然发现了一个问题。

该文件将存储在 windows appdata 文件夹中。 要将文件添加到电子邮件,我使用:

attachment = new System.Net.Mail.Attachment((Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/Folder1/Folder2/Folder3/result.txt"));

上面的代码有效,但是:

我目前遇到的问题是,如上所示,Folder2 将是一个包含数字、字母和单词 TEMP 的随机名称。

例如a12TEMP34b

我已经尝试并搜索了我是否能够以某种方式使用 *,但似乎无法正常工作。

有什么想法吗?

您可以将 Directory.GetDirectory 解析为字符串数组并获取该数组的第一个元素(如果您确定它始终是该路径)。

所以:

string staticPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/Folder1/";

string dynamicFolder = Directory.GetDirectory(staticPath, "*TEMP*")[0];

string finalPath = dynamicFolder + "/Folder3/result.txt"

您可以使用Directory.EnumerateDirectories搜索特定文件夹:

var folder1 = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Folder1");
var folder2 = Directory.EnumerateDirectories(folder1, "*TEMP*").Single();
var path = Path.Combine(folder2, "Folder3/result.txt");
attachment = new System.Net.Mail.Attachment(path)