从目录(winforms)加载附件
本文关键字:加载 winforms | 更新日期: 2023-09-27 17:50:01
我有一个类(GeneralSpecVersion)。一个属性是"published"。我想从这个类中获取一个对象,从系统上的已发布文件夹中向该对象添加文件,并加载该文件夹中的文件。由于可以有多个文件,因此该属性返回一个字符串列表。
我有这个"工作",但这需要我在我的类和winform格式代码中声明文件路径。我想最小化的形式代码,并保持我的逻辑在我的属性。因为我只是习惯使用简单的"get,set",我甚至不确定我是否正确设置了属性代码。
总之
从类中加载对象,为该对象添加文件名,加载文件
我班上public partial class GeneralSpecVersion : IEquatable<GeneralSpecVersion>, IComparable<GeneralSpecVersion>, IComparable
{
...
private List<string> _Published;
public List<string> Published
{
get {
string path = (Data.Database.Setting.GetApplicationOption("GenSpecAttachments", ""));
string published = System.IO.Path.Combine(path, Acronym + "''" + Major + "." + Minor + "''Published");
string invalid = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
foreach (char c in invalid)
{
Acronym = Acronym.Replace(c.ToString(), "_");
}
if (!Directory.Exists(published))
{
Directory.CreateDirectory(published);
}
return _Published;
}
set { _Published = value; }
}
}
Major和minor是类中的其他属性。
代码片段:
var genSpec = GeneralSpecification.GeneralSpecVersion.DataLoad("ELECTRICAL", "1", "01");
string publishedDir = "C:''NewTest''"
+ dgvAcronymSearch.Rows[0].Cells[0].Value.ToString() + "''"
+ dgvAcronymSearch.Rows[0].Cells[2].Value.ToString() + "."
+ dgvAcronymSearch.Rows[0].Cells[3].Value.ToString() + "''Published";
foreach(string filepath in Directory.GetFiles(publishedDir))
{
string file = Path.GetFileName(filepath);
genSpec.Published.Add(dgvAcronymSearch.Rows[0].Cells[0].Value.ToString());
Process.Start(filepath);
}
代码中有一个bug, Acronym
中的特殊字符在合并后被替换,必须在合并前完成
一般来说,在get
属性中创建目录不是一个好做法。Get应该能够在没有副作用的情况下被调用。
使用文件夹标签可能是一个值得考虑的方法。例如
private static readonly String PublishedFolderPattern = "<BaseFolder>''<FolderName>''<Major>.<Minor>''Published";
public static String GetPublishedFolder(String FolderName, int Major, int Minor, bool CreateDirectory = false) {
String BaseFolder = (Data.Database.Setting.GetApplicationOption("GenSpecAttachments", ""));
return GetPublishedFolder(BaseFolder, FolderName, Major, Minor, CreateDirectory);
}
public static String GetPublishedFolder(String BaseFolder, String FolderName, int Major, int Minor, bool CreateDirectory = false) {
// needs to come before
FolderName = FolderName.Trim('''');
string invalid = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
foreach (char c in invalid)
{
FolderName = FolderName.Replace(c, '_');
}
string published = PublishedFolderPattern;
published = published.Replace("<BaseFolder>", BaseFolder);
published = published.Replace("<FolderName>", FolderName);
published = published.Replace("<Major>", Major.ToString());
published = published.Replace("<Minor>", Minor.ToString());
if (CreateDirectory && !Directory.Exists(published))
Directory.CreateDirectory(published);
return published;
}