我正在开发一个项目,该项目从Azure Blob读取数据并将该数据保存到Object中。我目前遇到了一个问题。现在我的代码设置方式 - 如果没有虚拟文件夹,它将读取容器中的所有.txt数据。
但是,如果Azure容器中存在虚拟文件夹结构
我的代码会出错NullExceptionReference
。我的想法是进行if
检查以查看Azure容器中是否存在虚拟文件夹,如果是,则执行//some code
。有没有办法判断是否存在虚拟文件夹?
ReturnBlobObject()
private List<Blob> ReturnBlobObject(O365 o365)
{
List<Blob> listResult = new List<Blob>();
string textToFindPattern = "(\\/)";
string fileName = null;
string content = null;
//Loop through all Blobs and split the container form the file name.
foreach (var blobItem in o365.Container.ListBlobs(useFlatBlobListing: true))
{
string containerAndFileName = blobItem.Parent.Uri.MakeRelativeUri(blobItem.Uri).ToString();
string[] subString = Regex.Split(containerAndFileName, textToFindPattern);
//subString[2] is the name of the file.
fileName = subString[2];
content = ReadFromBlobStream(o365.Container.GetBlobReference(subString[2]));
Blob blobObject = new Blob(fileName, content);
listResult.Add(blobObject);
}
return listResult;
}
ReadFromBlobStream
private string ReadFromBlobStream(CloudBlob blob)
{
Stream stream = blob.OpenRead();
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
答案 0 :(得分:0)
我能够通过重构我的代码来解决这个问题。而不是使用Regex - 它返回了一些非常奇怪的行为,我决定退后一步思考问题。以下是我提出的解决方案。
<强> ReturnBlobObject()强>
private List<Blob> ReturnBlobObject(O365 o365)
{
List<Blob> listResult = new List<Blob>();
//Loop through all Blobs and split the container form the file name.
foreach (var blobItem in o365.Container.ListBlobs(useFlatBlobListing: true))
{
string fileName = blobItem.Uri.LocalPath.Replace(string.Format("/{0}/", o365.Container.Name), "");
string content = ReadFromBlobStream(o365.Container.GetBlobReference(fileName));
Blob blobObject = new Blob(fileName, content);
listResult.Add(blobObject);
}
return listResult;
}