code

파일을 byte []로 변환하는 안정적인 방법

codestyles 2020. 10. 13. 07:51
반응형

파일을 byte []로 변환하는 안정적인 방법


웹에서 다음 코드를 찾았습니다.

private byte [] StreamFile(string filename)
{
   FileStream fs = new FileStream(filename, FileMode.Open,FileAccess.Read);

   // Create a byte array of file stream length
   byte[] ImageData = new byte[fs.Length];

   //Read block of bytes from stream into the byte array
   fs.Read(ImageData,0,System.Convert.ToInt32(fs.Length));

   //Close the File Stream
   fs.Close();
   return ImageData; //return the byte data
}

C #에서 파일을 byte []로 변환하는 데 사용할 수있을만큼 신뢰할 수 있습니까? 아니면 더 좋은 방법이 있습니까?


byte[] bytes = System.IO.File.ReadAllBytes(filename);

그게 트릭을해야합니다. ReadAllBytes는 파일을 열고 내용을 새 바이트 배열로 읽은 다음 닫습니다. 해당 방법에 대한 MSDN 페이지다음과 같습니다 .


byte[] bytes = File.ReadAllBytes(filename) 

또는 ...

var bytes = File.ReadAllBytes(filename) 

모든 사람이 이미 말한 내용을 반복하지 말고 파일 조작을 위해 다음 치트 시트를 잘 보관하십시오.

  1. System.IO.File.ReadAllBytes(filename);
  2. File.Exists(filename)
  3. Path.Combine(folderName, resOfThePath);
  4. Path.GetFullPath(path); // converts a relative path to absolute one
  5. Path.GetExtension(path);

이 모든 답변은 .ReadAllBytes(). 비슷한 또 다른 질문 (코드를 리팩토링하려고했기 때문에 중복이라고 말하지 않겠습니다)이 여기에 질문되었습니다. C #에서 큰 파일을 바이트 배열로 읽는 가장 좋은 방법?

에 관한 게시물 중 하나에 댓글이 작성되었습니다 .ReadAllBytes().

File.ReadAllBytes throws OutOfMemoryException with big files (tested with 630 MB file 
and it failed) – juanjo.arana Mar 13 '13 at 1:31

나에게 더 나은 접근 방식은 다음과 같은 것입니다 BinaryReader.

public static byte[] FileToByteArray(string fileName)
{
    byte[] fileData = null;

    using (FileStream fs = File.OpenRead(fileName)) 
    { 
        var binaryReader = new BinaryReader(fs); 
        fileData = binaryReader.ReadBytes((int)fs.Length); 
    }
    return fileData;
}

하지만 그게 나야 ...

물론,이 모든 것은 byte[]일단 읽은 후에 처리 할 메모리가 있다고 가정 하고, File.Exists이 코드를 호출하기 전에했던 것처럼 계속하기 전에 파일이 있는지 확인 하지 않았습니다 .


일반 버전으로 충분 해 보입니다. 충분히 구체적인 경우 필요에 맞게 수정할 수 있습니다.

또한 파일이 존재하지 않거나 읽을 수없는 것과 같은 예외 및 오류 조건을 테스트합니다.

다음을 수행하여 공간을 절약 할 수도 있습니다.

 byte[] bytes = System.IO.File.ReadAllBytes(filename);

다른 사람들은 당신이 내장 된 File.ReadAllBytes. 기본 제공 방법은 좋지만 위에 게시 한 코드는 두 가지 이유로 취약하다는 점에 주목할 가치가 있습니다.

  1. Stream is IDisposable - you should place the FileStream fs = new FileStream(filename, FileMode.Open,FileAccess.Read) initialization in a using clause to ensure the file is closed. Failure to do this may mean that the stream remains open if a failure occurs, which will mean the file remains locked - and that can cause other problems later on.
  2. fs.Read may read fewer bytes than you request. In general, the .Read method of a Stream instance will read at least one byte, but not necessarily all bytes you ask for. You'll need to write a loop that retries reading until all bytes are read. This page explains this in more detail.

참고URL : https://stackoverflow.com/questions/1497997/reliable-way-to-convert-a-file-to-a-byte

반응형