Browse Source

Added new string extension: GetBytes

pull/301/head
Halil ibrahim Kalkan 8 years ago
parent
commit
5e86c1df5f
  1. 20
      src/Volo.Abp.Core/System/AbpStringExtensions.cs
  2. 25
      test/Volo.Abp.Core.Tests/System/StringExtensions_Tests.cs

20
src/Volo.Abp.Core/System/AbpStringExtensions.cs

@ -2,6 +2,7 @@ using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using JetBrains.Annotations;
using Volo.Abp;
namespace System
@ -404,5 +405,24 @@ namespace System
return str.Left(maxLength - postfix.Length) + postfix;
}
/// <summary>
/// Converts given string to a byte array using <see cref="Encoding.UTF8"/> encoding.
/// </summary>
public static byte[] GetBytes(this string str)
{
return str.GetBytes(Encoding.UTF8);
}
/// <summary>
/// Converts given string to a byte array using the given <paramref name="encoding"/>
/// </summary>
public static byte[] GetBytes([NotNull] this string str, [NotNull] Encoding encoding)
{
Check.NotNull(str, nameof(str));
Check.NotNull(encoding, nameof(encoding));
return encoding.GetBytes(str);
}
}
}

25
test/Volo.Abp.Core.Tests/System/StringExtensions_Tests.cs

@ -1,4 +1,5 @@
using Shouldly;
using System.Text;
using Shouldly;
using Volo.Abp.Localization;
using Xunit;
@ -193,6 +194,28 @@ namespace System
"MyValue2".ToEnum<MyEnum>().ShouldBe(MyEnum.MyValue2);
}
[Theory]
[InlineData("")]
[InlineData("MyStringİ")]
public void GetBytes_Test(string str)
{
var bytes = str.GetBytes();
bytes.ShouldNotBeNull();
bytes.Length.ShouldBeGreaterThan(0);
Encoding.UTF8.GetString(bytes).ShouldBe(str);
}
[Theory]
[InlineData("")]
[InlineData("MyString")]
public void GetBytes_With_Encoding_Test(string str)
{
var bytes = str.GetBytes(Encoding.ASCII);
bytes.ShouldNotBeNull();
bytes.Length.ShouldBeGreaterThan(0);
Encoding.ASCII.GetString(bytes).ShouldBe(str);
}
private enum MyEnum
{
MyValue1,

Loading…
Cancel
Save