.NET용 Azure Storage 파일 공유 클라이언트 라이브러리 - 버전 12.13.1

서버 버전: 2021-02-12, 2020-12-06, 2020-10-02, 2020-08-04, 2020-06-12, 2020-04-08, 2020-02-10, 2019-12-12, 2019-07-07 및 2019-02-02

Azure 파일 공유는 업계 표준 SMB(서버 메시지 블록) 프로토콜을 통해 액세스할 수 있는 클라우드에서 완전히 관리되는 파일 공유를 제공합니다. Azure File 공유는 Windows, Linux 및 macOS의 클라우드 또는 온-프레미스 배포를 통해 동시에 탑재될 수 있습니다. 또한 데이터가 사용되는 위치 근처에서 빠르게 액세스하기 위해 Azure 파일 동기화를 사용하여 Azure 파일 공유를 Windows Server에서 캐시할 수 있습니다.

소스 코드 | 패키지(NuGet) | API 참조 설명서 | REST API 설명서 | 제품 설명서

시작

패키지 설치

NuGet을 사용하여 .NET용 Azure Storage 파일 공유 클라이언트 라이브러리를 설치합니다.

dotnet add package Azure.Storage.Files.Shares

필수 구성 요소

이 패키지를 사용하려면 Azure 구독스토리지 계정이 필요합니다.

새 Storage 계정을 만들려면 Azure Portal, Azure PowerShell 또는 Azure CLI를 사용할 수 있습니다. 다음은 Azure CLI 사용 예입니다.

az storage account create --name MyStorageAccount --resource-group MyResourceGroup --location westus --sku Standard_LRS

주요 개념

Azure 파일 공유를 사용하여 다음을 수행할 수 있습니다.

  • 기존의 온-프레미스 파일 서버 또는 NAS 디바이스를 완전히 바꾸거나 보완합니다.
  • 파일 공유가 파일 애플리케이션 또는 사용자 데이터를 저장할 것으로 예상되는 클라우드로 애플리케이션을 "리프트 앤 시프트"합니다.
  • 공유 애플리케이션 설정, 진단 공유 및 개발/테스트/디버그 도구 파일 공유를 사용하여 새 클라우드 개발 프로젝트를 간소화합니다.

스레드로부터의 안전성

모든 클라이언트 instance 메서드는 스레드로부터 안전하고 서로 독립적임을 보장합니다(지침). 이렇게 하면 스레드 간에 클라이언트 인스턴스를 다시 사용하는 것이 항상 안전합니다.

추가 개념

클라이언트 옵션 | 응답 | 에 액세스 장기 실행 작업 | 오류 | 처리 진단 | 조롱 | 클라이언트 수명

예제

공유 만들기 및 파일 업로드

// Get a connection string to our Azure Storage account.  You can
// obtain your connection string from the Azure Portal (click
// Access Keys under Settings in the Portal Storage account blade)
// or using the Azure CLI with:
//
//     az storage account show-connection-string --name <account_name> --resource-group <resource_group>
//
// And you can provide the connection string to your application
// using an environment variable.
string connectionString = "<connection_string>";

// Name of the share, directory, and file we'll create
string shareName = "sample-share";
string dirName = "sample-dir";
string fileName = "sample-file";

// Path to the local file to upload
string localFilePath = @"<path_to_local_file>";

// Get a reference to a share and then create it
ShareClient share = new ShareClient(connectionString, shareName);
share.Create();

// Get a reference to a directory and create it
ShareDirectoryClient directory = share.GetDirectoryClient(dirName);
directory.Create();

// Get a reference to a file and upload it
ShareFileClient file = directory.GetFileClient(fileName);
using (FileStream stream = File.OpenRead(localFilePath))
{
    file.Create(stream.Length);
    file.UploadRange(
        new HttpRange(0, stream.Length),
        stream);
}

파일 다운로드

string connectionString = "<connection_string>";

// Name of the share, directory, and file we'll download from
string shareName = "sample-share";
string dirName = "sample-dir";
string fileName = "sample-file";

// Path to the save the downloaded file
string localFilePath = @"<path_to_local_file>";

// Get a reference to the file
ShareClient share = new ShareClient(connectionString, shareName);
ShareDirectoryClient directory = share.GetDirectoryClient(dirName);
ShareFileClient file = directory.GetFileClient(fileName);

// Download the file
ShareFileDownloadInfo download = file.Download();
using (FileStream stream = File.OpenWrite(localFilePath))
{
    download.Content.CopyTo(stream);
}

공유 트래버스

// Connect to the share
string connectionString = "<connection_string>";
string shareName = "sample-share";
ShareClient share = new ShareClient(connectionString, shareName);

// Track the remaining directories to walk, starting from the root
var remaining = new Queue<ShareDirectoryClient>();
remaining.Enqueue(share.GetRootDirectoryClient());
while (remaining.Count > 0)
{
    // Get all of the next directory's files and subdirectories
    ShareDirectoryClient dir = remaining.Dequeue();
    foreach (ShareFileItem item in dir.GetFilesAndDirectories())
    {
        // Print the name of the item
        Console.WriteLine(item.Name);

        // Keep walking down directories
        if (item.IsDirectory)
        {
            remaining.Enqueue(dir.GetSubdirectoryClient(item.Name));
        }
    }
}

비동기 API

동기 API와 비동기 API를 모두 완벽하게 지원합니다.

string connectionString = "<connection_string>";

// Name of the share, directory, and file we'll download from
string shareName = "sample-share";
string dirName = "sample-dir";
string fileName = "sample-file";

// Path to the save the downloaded file
string localFilePath = @"<path_to_local_file>";

// Get a reference to the file
ShareClient share = new ShareClient(connectionString, shareName);
ShareDirectoryClient directory = share.GetDirectoryClient(dirName);
ShareFileClient file = directory.GetFileClient(fileName);

// Download the file
ShareFileDownloadInfo download = await file.DownloadAsync();
using (FileStream stream = File.OpenWrite(localFilePath))
{
    await download.Content.CopyToAsync(stream);
}

문제 해결

모든 Azure Storage 파일 공유 서비스 작업은 유용한 ErrorCodes와 함께 실패 시 RequestFailedException을 throw합니다. 이러한 오류 중 대부분은 복구할 수 있습니다.

// Connect to the existing share
string connectionString = "<connection_string>";
string shareName = "sample-share";
ShareClient share = new ShareClient(connectionString, shareName);

try
{
    // Try to create the share again
    share.Create();
}
catch (RequestFailedException ex)
    when (ex.ErrorCode == ShareErrorCode.ShareAlreadyExists)
{
    // Ignore any errors if the share already exists
}

다음 단계

파일 샘플 시작:

  1. 헬로 월드: 파일 업로드, 파일 다운로드 및 공유 트래버스(또는 비동기)
  2. 인증: 연결 문자열, 공유 키 및 공유 액세스 서명을 사용하여 인증합니다.

참여

이 라이브러리의 빌드, 테스트 및 기여에 대한 자세한 내용은 Storage CONTRIBUTING.md 참조하세요.

이 프로젝트에 대한 기여와 제안을 환영합니다. 대부분의 경우 기여하려면 권한을 부여하며 실제로 기여를 사용할 권한을 당사에 부여한다고 선언하는 CLA(기여자 라이선스 계약)에 동의해야 합니다. 자세한 내용은 cla.microsoft.com.

이 프로젝트에는 Microsoft Open Source Code of Conduct(Microsoft 오픈 소스 준수 사항)가 적용됩니다. 자세한 내용은 Code of Conduct FAQ(규정 FAQ)를 참조하세요. 또는 추가 질문이나 의견은 opencode@microsoft.com으로 문의하세요.

Impressions