programing

바이트[] 배열을 C#의 파일에 쓸 수 있습니까?

mailnote 2023. 5. 26. 22:07
반응형

바이트[] 배열을 C#의 파일에 쓸 수 있습니까?

나는 그것을 쓰려고 노력하고 있습니다.Byte[]파일에 대한 전체 파일을 나타내는 배열입니다.

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

이는 주로 수신을 보장하기 위한 것입니다.TCPClient다음 스트림에 대한 준비가 완료되었으며 수신 측과 처리 측을 분리합니다.

FileStream클래스는 바이트 배열을 인수 또는 다른 스트림 개체로 사용하지 않습니다(바이트를 쓸 수 있음).

원본(TCP Client를 사용하는 스레드)과 다른 스레드로 처리하는 것을 목표로 합니다.

이걸 어떻게 구현해야 할지 모르겠는데, 어떻게 해야 하나요?

질문의 첫 번째 문장을 기반으로 합니다. "파일에 전체 파일나타내는 Byte[] 배열을 쓰려고 합니다."

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

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

여기에 문서화됨:

System.IO.File.WriteAllBytesMSDN

를 사용할 수 있습니다.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파트...독자를 위한 연습으로 남겨졌다고 치자 ;-)

정적 방법이 있습니다.System.IO.File.WriteAllBytes

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

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

FileStream을 사용할 수 있습니다.쓰기(byte[] array, int offset, int count) 메서드를 사용하여 쓰기를 수행합니다.

어레이 이름이 "myArray"이면 코드가 "myArray"가 됩니다.

myStream.Write(myArray, 0, myArray.count);

네, 왜요?

fs.Write(myByteArray, 0, myByteArray.Length);

이진 판독기 사용:

/// <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;
}

Asp.net (c#)

응용프로그램이 호스트되는 서버 경로입니다.

var path = @"C:\Websites\mywebsite\profiles\";

//바이트 배열의 파일

var imageBytes = client.DownloadData(imagePath);

//파일 확장명

var fileExtension = System.IO.Path.GetExtension(imagePath);

//지정된 경로에 파일을 기록(저장)합니다.직원 ID를 파일 이름 및 파일 확장명으로 추가합니다.

File.WriteAllBytes(path + dataTable.Rows[0]["empid"].ToString() + fileExtension, imageBytes);

다음 단계:

iis 사용자를 위해 프로필 폴더에 대한 액세스 권한을 제공해야 할 수 있습니다.

  1. 프로필 폴더를 마우스 오른쪽 버튼으로 클릭합니다.
  2. 보안 탭으로 이동
  3. 편집을 클릭합니다.
  4. "IIS_IUSRS"를 완전히 제어합니다(이 사용자가 존재하지 않는 경우 Add(추가)를 클릭하고 "IIS_IUSRS"를 입력한 후 "Check Names(이름 확인)"를 클릭합니다.

언급URL : https://stackoverflow.com/questions/381508/can-a-byte-array-be-written-to-a-file-in-c

반응형