C #에서 Byte [] 배열을 파일에 쓸 수 있습니까?


344

Byte[]완전한 파일을 나타내는 배열을 파일에 쓰려고 합니다.

클라이언트의 원본 파일은 TCP를 통해 전송 된 다음 서버에서 수신됩니다. 수신 된 스트림은 바이트 배열로 읽은 다음이 클래스에 의해 처리되도록 전송됩니다.

이것은 주로 수신 TCPClient이 다음 스트림에 대한 준비를하고 수신단을 처리 단에서 분리하기위한 것이다.

FileStream클래스는 인수 나 (당신이 그것에 바이트를 작성할 수 않는) 다른 스트림 객체로 바이트 배열을지지 않습니다.

원본과 다른 스레드 (TCPClient가있는 스레드)로 처리를 수행하려고합니다.

이것을 구현하는 방법을 모르겠습니다. 어떻게 시도해야합니까?

답변:


728

질문의 첫 문장을 바탕으로 : " 완전한 파일나타내는 Byte [] 배열을 파일 에 쓰려고 합니다."

최소 저항 경로는 다음과 같습니다.

File.WriteAllBytes(string path, byte[] bytes)

여기에 문서화 :

System.IO.File.WriteAllBytes -MSDN


40

BinaryWriter객체 를 사용할 수 있습니다 .

protected bool SaveData(string FileName, byte[] Data)
{
    BinaryWriter Writer = null;
    string Name = @"C:\temp\yourfile.name";

    try
    {
        // Create a new stream to write to the file
        Writer = new BinaryWriter(File.OpenWrite(Name));

        // Writer raw data                
        Writer.Write(Data);
        Writer.Flush();
        Writer.Close();
    }
    catch 
    {
        //...
        return false;
    }

    return true;
}

편집 : 죄송합니다, finally부품을 잊어 버렸습니다 ... 독자의 연습으로 남았습니다. ;-)


압축 된 데이터를 받았으며이를 Byte []로 압축 해제했습니다. 위의 기능을 사용하여 파일을 다시 만들 수 있습니까? 온라인 튜토리얼 또는 데모?
Cannon

@buffer_overflow : 원본 파일을 다시 가져 오려면 먼저 압축해야합니다. 가능한 구현을 위해 데코레이터 패턴을 살펴보십시오 : en.wikipedia.org/wiki/Decorator_pattern
Treb

2
BinaryWriter일회용이므로 using블록 내에서 사용해야합니다 . 그것은 또한 소스 코드 가 처리하는 동안 정리를 수행한다는 것을 보여주기 때문에 여분의 호출을 생략 할 수 있음을 의미합니다 .
Jeff B


11

System.IO.BinaryWriter스트림을 사용 하여이 작업을 수행 할 수 있습니다 .

var bw = new BinaryWriter(File.Open("path",FileMode.OpenOrCreate);
bw.Write(byteArray);

7
그냥 bw.flush와 bw.close를 추가 한 후에 추가하고 싶다
dekdev

6
@dekdev : 플러시 로 호출 Flush()하기 전에는 아무런 요점이 없습니다 . 플러시하고 닫을 절 을 사용하는 것이 더 좋습니다 . Close()Close()using
Tomas

1
Dispose를 사용하는 것을 잊지 마십시오.
vitor_gaudencio_oliveira



1

BinaryReader를 사용해보십시오.

/// <summary>
/// Convert the Binary AnyFile to Byte[] format
/// </summary>
/// <param name="image"></param>
/// <returns></returns>
public static byte[] ConvertANYFileToBytes(HttpPostedFileBase image)
{
    byte[] imageBytes = null;
    BinaryReader reader = new BinaryReader(image.InputStream);
    imageBytes = reader.ReadBytes((int)image.ContentLength);
    return imageBytes;
}
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.