Skip to main content Link Menu Expand (external link) Document Search Copy Copied

Algorytm C# - Przykład 3: pobranie załącznika

Podsumowanie:

Poniższy kod akcji C# pobiera załącznik o podanym identyfikatorze i zapisuje do pliku w określonej lokalizacji.

using System;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using CSharpScript.WebServiceRunner.Models;

var baseUri = new System.Uri(TenantBaseUrl);
var _endpointUri = new System.Uri(baseUri, "publicapi/attachment/downloadAttachment");
var _authUri = new System.Uri(baseUri, "connect/token");
var _userName = "tutaj nazwa użytkownika, który ma dostęp do public-api";
var _userPassword = "tutaj hasło użytkownika";
var _scope = "public-api";
var _clientSecret = "secret";
var _clientId = "openjs";


var attachmentId = 0; //tutaj podajemy id załącznika, którego plik chcemy pobrać
var pathToFile = @"C:\temp\jakis plik.ext"; //ścieżka zapisu załącznika wraz z nazwą pliku

var request = new CSharpScript.WebServiceRunner.Models.RestRequestModel()
{
    Method = System.Net.Http.HttpMethod.Get,
    Url = $"{_endpointUri.AbsoluteUri}?id={attachmentId}",
    AuthType = ApiConnector.Enums.AuthType.OAuth2Password,
    AuthUrl = _authUri.AbsoluteUri,
    UserName = _userName,
    Password = _userPassword,
    ClientId = _clientId,
    ClientSecret = _clientSecret,
    Scope = _scope,
};

using (var client = new HttpClient())
{
    await PrepareAuth(client, request.AuthUrl, request.UserName, request.Password, request.ClientId, request.ClientSecret, request.Scope);
    
    var response = await client.GetAsync(request.Url);
    response.EnsureSuccessStatusCode();
    var fileContent = await response.Content.ReadAsByteArrayAsync();
    await SaveFile(pathToFile, fileContent);
}

private Task SaveFile(string pathToFile, byte[] fileContent)
{
    return System.IO.File.WriteAllBytesAsync(pathToFile, fileContent);
}

private async Task PrepareAuth(HttpClient client, string authServer, string userName, string password, string clientId, string clientSecret, string scope)
{
    var token = await GetBearerToken(authServer, userName, password, clientId, clientSecret, scope);
    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
}

private async Task<string> GetBearerToken(string authServer, string userName, string password, string clientId, string clientSecret, string scope)
{
    var client = new HttpClient();
    client.DefaultRequestHeaders.Accept.Clear();
    client.Timeout = TimeSpan.FromMinutes(10);

    var contentValues = new System.Collections.Generic.Dictionary<string, string>();
    contentValues.Add("grant_type", "password");
    
    if (!string.IsNullOrWhiteSpace(clientId))
    {
        contentValues.Add("client_id", clientId);
    }

    if (!string.IsNullOrWhiteSpace(clientSecret))
    {
        contentValues.Add("client_secret", clientSecret);
    }

    if (!string.IsNullOrWhiteSpace(scope))
    {
        contentValues.Add("scope", scope);
    }

    if (!string.IsNullOrWhiteSpace(password))
    {
        contentValues.Add("password", password);
    }

    if (!string.IsNullOrWhiteSpace(userName))
    {
        contentValues.Add("username", userName);
    }

    var content = new FormUrlEncodedContent(contentValues);

    var httpResponse = await client.PostAsync(authServer, content, default);
    if (httpResponse == null)
    {
        throw new Shared.Exceptions.TranslatedException("Api.ActionModule.ConnectionFailed");
    }

    var response = await httpResponse.Content.ReadAsStringAsync();
    dynamic objectResponse = Newtonsoft.Json.JsonConvert.DeserializeObject(response);

    if (objectResponse == null || objectResponse.access_token == null)
    {
        throw new Exception(response);
    }

    return objectResponse.access_token;
}
|← Algorytm C# - Przykład 2: dodanie załącznika |↑ Do góry |→ Algorytm C# - Przykład 4: usunięcie załącznika |

Copyright © 2025 OPTEAM SA. Theme Copyright © 2017-2020 Patrick Marsceill. Distributed by an MIT license.