问题描述
我的任务是制作一个.NET Core 3.1控制台应用程序,该应用程序将在AWS平台上的Linux docker容器中运行,并连接到Azure文件存储以读取和写入文件。我曾经是C#程序员,但到目前为止与容器或Azure无关。
我已收到以下格式的Azure连接字符串: DefaultEndpointsProtocol = https; AccountName = [ACCOUNT_NAME_HERE]; AccountKey = [ACCOUNT_KEY_HERE]; EndpointSuffix = core.windows.net
但是,按照我在网上看到的示例,
- 右键单击VS2019中的项目,然后添加Connected Service。
- 从列表中选择Azure存储。
- 连接到您的Azure存储帐户
我没有那个,我只有一个连接字符串。
我发现了以下示例:
但这两个都使用:
Microsoft.Azure.Storage.Common
,在依赖关系下,它具有.NET Standard和.NET Framework。我认为这些不会在linux docker容器中运行。一旦我确定了docker容器的工作能力,我将进行测试以确认这一点。
任何人都可以从在AWS平台上的Linux docker容器中运行的.NET Core 3.1控制台应用程序阐明我如何才能连接到Azure文件存储以使用概述的Azure连接字符串格式读取和写入文件以上?
解决方法
如果您专注于如何在Connected Service中添加服务依赖项,那么如果您没有Azure帐户登录电子邮件/密码,则无法添加服务。
从您的描述看来,您似乎只想使用C#控制台应用程序从存储的文件共享中读写文件。因此,您无需添加项目服务,只需在控制台应用程序中添加代码即可。
这是一个简单的代码:
using System;
using System.IO;
using System.Text;
using Azure;
using Azure.Storage.Files.Shares;
namespace ConsoleApp4
{
class Program
{
static void Main(string[] args)
{
string con_str = "DefaultEndpointsProtocol=https;AccountName=0730bowmanwindow;AccountKey=xxxxxx;EndpointSuffix=core.windows.net";
string sharename = "test";
string filename = "test.txt";
string directoryname = "testdirectory";
ShareServiceClient shareserviceclient = new ShareServiceClient(con_str);
ShareClient shareclient = shareserviceclient.GetShareClient(sharename);
ShareDirectoryClient sharedirectoryclient = shareclient.GetDirectoryClient(directoryname);
//write data.
ShareFileClient sharefileclient_in = sharedirectoryclient.CreateFile(filename,1000);
string filecontent_in = "This is the content of the file.";
byte[] byteArray = Encoding.UTF8.GetBytes(filecontent_in);
MemoryStream stream1 = new MemoryStream(byteArray);
stream1.Position = 0;
sharefileclient_in.Upload(stream1);
//read data.
ShareFileClient sharefileclient_out = sharedirectoryclient.GetFileClient(filename);
Stream stream2 = sharefileclient_out.Download().Value.Content;
StreamReader reader = new StreamReader(stream2);
string filecontent_out = reader.ReadToEnd();
Console.WriteLine(filecontent_out);
}
}
}