我在Azure中创建了文件存储,可以访问它并验证目录是否存在。如何在云目录中创建文件并写入?
一般信息,如何使用Azure文件存储:https://docs.microsoft.com/en-us/azure/storage/files/storage-dotnet-how-to-use-files如何创建文件并添加一些文本:https://www.youtube.com/watch?v=HnkqqLOOnR4
// Create a CloudFileClient object for credentialed access to Azure Files.
CloudFileClient fileClient = storageAccount.CreateCloudFileClient();
// Get a reference to the file share we created previously.
CloudFileShare share = fileClient.GetShareReference("logs");
// Ensure that the share exists.
if (share.Exists())
{
// Get a reference to the root directory for the share.
CloudFileDirectory rootDir = share.GetRootDirectoryReference();
// Get a reference to the directory we created previously.
CloudFileDirectory sampleDir = rootDir.GetDirectoryReference("CustomLogs");
// Ensure that the directory exists.
if (sampleDir.Exists())
{
// Get a reference to the file we created previously.
CloudFile file = sampleDir.GetFileReference("Log1.txt");
// Ensure that the file exists.
if (file.Exists())
{
// Write the contents of the file to the console window.
Console.WriteLine(file.DownloadTextAsync().Result);
}
}
}
如果您正在寻找一个在C#中将文件上传到Azure容器的解决方案,这里有一个我用作将文件上传到Azure的实用程序的函数
public static string UploadBlob(string blobContainerName, string key, Stream sourceStrem, string contentType)
{
//getting the storage account
string uri = null;
try
{
blobContainerName = blobContainerName.ToLowerInvariant();
string azureStorageAccountConnection =
ConfigurationManager.ConnectionStrings["AzureStorageAccount"].ConnectionString;
CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(azureStorageAccountConnection);
CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
CloudBlobContainer container = cloudBlobClient.GetContainerReference(blobContainerName);
container.CreateIfNotExists();
CloudBlockBlob blob = container.GetBlockBlobReference(key);
blob.Properties.ContentType = contentType;
blob.UploadFromStream(sourceStrem);
uri = blob.Uri.ToString();
}
catch (Exception exception)
{
if (_logger.IsErrorEnabled)
_logger.Error(exception.Message, exception);
}
return uri;
}
其中blobContainerName是Azure上的容器,key是要存储此blob的文件的名称,第三个参数是文件流,最后一个是内容类型。
希望能帮助到你