microsoft/healthcare-shared-components
Publicmirrored from https://github.com/microsoft/healthcare-shared-componentsAvailable
src/Microsoft.Health.Core/Extensions/ByteExtensions.cs
32lines · modecode
| 1 | // ------------------------------------------------------------------------------------------------- |
| 2 | // Copyright (c) Microsoft Corporation. All rights reserved. |
| 3 | // Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. |
| 4 | // ------------------------------------------------------------------------------------------------- |
| 5 | |
| 6 | using System; |
| 7 | using System.Text; |
| 8 | using EnsureThat; |
| 9 | |
| 10 | namespace Microsoft.Health.Core.Extensions |
| 11 | { |
| 12 | public static class ByteExtensions |
| 13 | { |
| 14 | /// <summary> |
| 15 | /// Encodes a Byte array to Base64 safely, this can be used in URLs. |
| 16 | /// </summary> |
| 17 | /// <param name="bytes">The bytes to encode.</param> |
| 18 | /// <returns>An encoded string that's safe to be used in URLs.</returns> |
| 19 | public static string ToSafeBase64(this byte[] bytes) |
| 20 | { |
| 21 | EnsureArg.IsNotNull(bytes, nameof(bytes)); |
| 22 | |
| 23 | string base64 = Convert.ToBase64String(bytes); |
| 24 | |
| 25 | StringBuilder sb = new StringBuilder(base64.TrimEnd('=')); |
| 26 | |
| 27 | sb.Replace('+', '-').Replace('/', '_'); |
| 28 | |
| 29 | return sb.ToString(); |
| 30 | } |
| 31 | } |
| 32 | } |
| 33 | |