Logo
技术 C#

C# byte[]和文件FileStream相互转化

photo
Pastore Antonio

2022年06月01日

using System.IO;

//读filename到byte[]

        
private byte[] ReadFile(string fileName)

        
{

            FileStream pFileStream 
= null;

            
byte[] pReadByte = new byte[0];

            
try

            
{

                pFileStream 
= new FileStream(fileName, FileMode.Open, FileAccess.Read);

                BinaryReader r 
= new BinaryReader(pFileStream);

                r.BaseStream.Seek(
0, SeekOrigin.Begin);    //将文件指针设置到文件开

                pReadByte 
= r.ReadBytes((int)r.BaseStream.Length);

                
return pReadByte;

            }


            
catch

            
{

                
return pReadByte;

            }


            
finally

            
{

                
if (pFileStream != null)

                    pFileStream.Close();

            }


        }


        
//写byte[]到fileName

        
private bool writeFile(byte[] pReadByte, string fileName)

        
{

            FileStream pFileStream 
= null;

 

            
try

            
{

                pFileStream 
= new FileStream(fileName, FileMode.OpenOrCreate);

                pFileStream.Write(pReadByte, 
0, pReadByte.Length);

 

            }


            
catch

            
{

                
return false;

            }


            
finally

            
{

                
if (pFileStream != null)

                    pFileStream.Close();

            }


            
return true;

        }


         测试

        
private void button6_Click(object sender, EventArgs e)

        
{

             
//by 闫磊 Email:Landgis@126.com,yanleigis@21cn.com 2007.11.23

 

byte[] b = ReadFile(@”c:\u.jpg);

            
if (writeFile(b, @”c:\u1.jpg))

            
{

                MessageBox.Show(
成功);

            }


            
else { MessageBox.Show(失败); }

        }


本文为原创文章,请注意保留出处!
修复群晖Synology Drive client右键菜单缺失问题 Local, clean & environmental 作者:Pastore Antonio
1808 浏览量
1785 浏览量
configure: error: Package requirements (oniguruma) were not met Local, clean & environmental 作者:Pastore Antonio
1526 浏览量
Adobe Acrobat Pro 激活 Local, clean & environmental 作者:Pastore Antonio
1522 浏览量
追寻日出,找回自己 Local, clean & environmental 作者:Pastore Antonio
1489 浏览量