문제

system.io.stream에 StringBuilder를 작성하는 가장 좋은 방법은 무엇입니까?

나는 현재하고있다 :

StringBuilder message = new StringBuilder("All your base");
message.Append(" are belong to us");

System.IO.MemoryStream stream = new System.IO.MemoryStream();
System.Text.ASCIIEncoding encoding = new ASCIIEncoding();
stream.Write(encoder.GetBytes(message.ToString()), 0, message.Length);
도움이 되었습니까?

해결책

스트림에 글을 쓰면 StringBuilder를 사용하지 마십시오. 스트림 라이터:

using (var memoryStream = new MemoryStream())
using (var writer = new StreamWriter(memoryStream ))
{
    // Various for loops etc as necessary that will ultimately do this:
    writer.Write(...);
}

다른 팁

이것이 최선의 방법입니다. 다른 현명한 상실 StringBuilder와 다음과 같은 것을 사용합니다.

using (MemoryStream ms = new MemoryStream())
{
    using (StreamWriter sw = new StreamWriter(ms, Encoding.Unicode))
    {
        sw.WriteLine("dirty world.");
    }
    //do somthing with ms
}

아마도 유용 할 것입니다.

var sb= new StringBuilder("All your money");
sb.Append(" are belong to us, dude.");
var myString = sb.ToString();
var myByteArray = System.Text.Encoding.UTF8.GetBytes(myString);
var ms = new MemoryStream(myByteArray);
// Do what you need with MemoryStream

유스 케이스에 따라 StringWriter로 시작하는 것이 합리적 일 수도 있습니다.

StringBuilder sb = null;

// StringWriter - a TextWriter backed by a StringBuilder
using (var writer = new StringWriter())
{
    writer.WriteLine("Blah");
    . . .
    sb = writer.GetStringBuilder(); // Get the backing StringBuilder out
}

// Do whatever you want with the StringBuilder

StringBuilder와 같은 것을 사용하려면 더 깨끗하기 때문에 통과하고 작업 할 수 있으므로 다음 StringBuilder 대체와 같은 것을 사용할 수 있습니다.

가장 중요한 것은 다른 일은 문자열이나 바이 테레로 먼저 조립하지 않고 내부 데이터에 액세스 할 수 있다는 것입니다. 즉, 메모리 요구 사항을 두 배로 늘릴 필요가 없으며 전체 객체에 맞는 인접한 메모리 덩어리를 할당하려고 할 위험이 있습니다.

참고 : 더 나은 옵션이 있다고 확신합니다. List<string>() 내부적으로 그러나 이것은 단순했고 나의 목적에 충분한 것으로 판명되었습니다.

public class StringBuilderEx
{
    List<string> data = new List<string>();
    public void Append(string input)
    {
        data.Add(input);
    }
    public void AppendLine(string input)
    {
        data.Add(input + "\n");
    }
    public void AppendLine()
    {
        data.Add("\n");
    }

    /// <summary>
    /// Copies all data to a String.
    /// Warning: Will fail with an OutOfMemoryException if the data is too
    /// large to fit into a single contiguous string.
    /// </summary>
    public override string ToString()
    {
        return String.Join("", data);
    }

    /// <summary>
    /// Process Each section of the data in place.   This avoids the
    /// memory pressure of exporting everything to another contiguous
    /// block of memory before processing.
    /// </summary>
    public void ForEach(Action<string> processData)
    {
        foreach (string item in data)
            processData(item);
    }
}

이제 다음 코드를 사용하여 전체 내용을 파일에 버릴 수 있습니다.

var stringData = new StringBuilderEx();
stringData.Append("Add lots of data");

using (StreamWriter file = new System.IO.StreamWriter(localFilename))
{
    stringData.ForEach((data) =>
    {
        file.Write(data);
    });
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top