我正在创建一个控制台应用程序,为每个实体下载附件(注释)。想法是创建一个主文件夹,其中包含实体名称,实体文件夹的子文件夹,以注释的对象ID命名,每个子文件夹将是与文件夹的id对应的文件。到目前为止,这是我的代码:
string filepath = "C:\\";
String fetchXmlNote = "<fetch mapping='logical' count='20'>";
fetchXmlNote += "<entity name='annotation'>";
fetchXmlNote += "<attribute name='filename'/>";
fetchXmlNote += "<attribute name='documentbody'/>";
fetchXmlNote += "<attribute name='mimetype'/>";
fetchXmlNote += "<attribute name='objectid'/>";
fetchXmlNote += "<link-entity name='" +EntityName+ "' from='" + EntityName + "id' to='objectid'>";
fetchXmlNote += "</link-entity>";
fetchXmlNote += "</entity>";
fetchXmlNote += "</fetch>";
Microsoft.Xrm.Sdk.EntityCollection result = service.RetrieveMultiple(new FetchExpression(fetchXmlNote));
if (result != null)
{
FilePath = FilePath + EntityName + "\\";
foreach (Entity e in result.Entities)
{
Directory.CreateDirectory(FilePath + e.GetAttributeValue<EntityReference>("objectid").Id.ToString());
if (!String.IsNullOrWhiteSpace(e.Attributes["documentbody"].ToString()))
{
byte[] data = Convert.FromBase64String(e.Attributes["documentbody"].ToString());
File.WriteAllBytes(FilePath + e.Attributes["filename"].ToString(), data);
}
直到现在我已经制作了用于下载文件的fetch xml,并且我已经为每个objectid创建了文件夹,但我需要将每个文件放在相应的文件夹中。 请注意,需要检查重复。 任何帮助表示赞赏。
答案 0 :(得分:0)
尝试检查每个file/folder
是否已存在
using System.IO;
if (result != null)
{
FilePath = FilePath + EntityName;
if(CheckIfFolderExists(FilePath + EntityName)==false) //Check primary folder, if do not exists create one
{
Directory.CreateDirectory(FilePath + EntityName); //Create primary folder
}
FilePath+= "\\";
foreach (Entity e in result.Entities)
{
if(CheckIfFolderExists(FilePath + e.GetAttributeValue<EntityReference>("objectid").Id.ToString()))==false) //Check subfolder, if do not exists create one
{
Directory.CreateDirectory(FilePath + e.GetAttributeValue<EntityReference>("objectid").Id.ToString()); //Create subfolder inside primary folder
}
//Also check here, if file with the same name already exists, if not create one
if (!String.IsNullOrWhiteSpace(e.Attributes["documentbody"].ToString()) && !File.Exists(FilePath + e.Attributes["filename"].ToString()))
{
byte[] data = Convert.FromBase64String(e.Attributes["documentbody"].ToString());
File.WriteAllBytes(FilePath + e.Attributes["filename"].ToString(), data);
}
}
}
public static bool CheckIfFolderExists(string path)
{
return Directory.Exists(path);
}