2016-12-21 1 views
1

Memorystream에서 간단한 Filestream으로 작성해야합니다. 문제는 내 memorystream 파일 이름 및 해당 바이트 시퀀스를 "|"로 구분 된 보유하고 있습니다. 그래서 다음과 같은 것입니다 : name.extension | BYTES. 내가 지금 쓰는 데 사용하는 코드는 다음과 같습니다 내가 파일을 작성하는 방법0이 아닌 위치에서 시작하는 Memorystream에서 FileStream에 어떻게 쓸 수 있습니까?

Dim fs As FileStream = File.Create(sf.FileName()) 'SaveFileDialog 
     ms.Seek(j, SeekOrigin.Begin) 'starting to write after "|" char 

     Do 
      ms.Read(temp, 0, 1) 
      fs.Write(temp, 0, 1) 
      j += 1 
     Loop While ms.Length - j <> 0 'YES... byte after byte 

     fs.Close() 
     fs.Dispose() 
     ms.close() 
     ms.Dispose() 

은 다음과 같습니다

Dim j As Integer = 1 
    Dim name As String 
    name = "" 
    ms.Read(temp, 0, 1) 
    Do While (UTF8.GetString(temp, 0, 1) <> "|") 
     name += UTF8.GetString(temp, 0, 1) 
     j += 1 
     ms.Read(temp, 0, 1) 
    Loop 

그건 내가 파일의 이름이 얻을 방법입니다. 더 잘 쓰여질 수있는 일이있을 수도 있다는 것을 알고 있습니다. 그러나 그것이 제가 당신의 도움을 요청하는 이유입니다. MememoryStream.WriteTo (FileStream)를 사용하려고 시도했지만 파일 이름에서도 쓰기 시작합니다. 코드를 개선 할 수 있습니까? 고마워요!

+1

당신의 접근 방법이 좋습니다. 버퍼 크기를 1에서 늘리십시오. 그렇지 않으면 작동하는 경우 하루로 지정해야합니다. –

+2

'Seek' 후'ms.CopyTo (fs)'를 시도하십시오. – Mark

+0

@GuillaumeCR 나는 그렇게 생각했다. 그러나 버퍼 크기가 memorystream의 남은 바이트를 초과 할 때를 알아야한다. 내가 맞습니까? – Dadex

답변

1

Mark의 제안을 읽은 후, 나는 그의 접근 방식이 훨씬 좋다고 생각합니다. 스트림은 서로 연결될 예정 이었으므로 프레임 워크가 수행 한 작업을 수동으로 수행하지 마십시오. 다음은 효과가있는 테스트입니다.

using (var ms = new MemoryStream()) 
{ 
    //Prepare test data. 
    var text = "aFileName.txt|the content"; 
    var bytes = Encoding.UTF8.GetBytes(text); 
    ms.Write(bytes, 0, bytes.Length); 
    //Seek back to origin to simulate a fresh stream 
    ms.Seek(0, SeekOrigin.Begin); 

    //Read until you've consumed the | or you run out of stream. 
    var oneByte = 0; 
    while (oneByte >= 0 && Convert.ToChar(oneByte) != '|') 
    { 
     oneByte = ms.ReadByte(); 
    } 

    //At this point you've consumed the filename and the pipe. 
    //Your memory stream is now at the proper position and you 
    //can simply tell it to dump its content into the filestream. 
    using (var fs = new FileStream("test.txt", FileMode.Create)) 
    { 
     ms.CopyTo(fs); 
    } 
} 

스트림은 일회용 개체입니다. 닫고 처리하는 대신 예외가 발생하더라도 'using'구문을 사용하여 처리해야합니다.

+0

몇 가지 테스트를했는데 실제로는 꽤 잘 작동합니다. 고마워요! – Dadex

관련 문제