2011-11-26 69 views
0

我有代码使用OpenFileDialog读取数据(浏览),我将 读取的是图像,我将进入数据库,因此我做了 转换为字节数据类型,但是当我不浏览,并立即按下保存按钮, 会出错误对话框,任何人都可以帮我解决这个.. 的错误何以是我更换一个消息..打开文件时出错(浏览)

byte[] ReadFile(string sPath) 
{ 
    //Initialize byte array with a null value initially. 
    byte[] data = null; 

    //Use FileInfo object to get file size. 
    FileInfo fInfo = new FileInfo(sPath); 
    long numBytes = fInfo.Length; 

    //Open FileStream to read file 
    FileStream fStream = new FileStream(sPath, FileMode.Open, FileAccess.Read); 

    //Use BinaryReader to read file stream into byte array. 
    BinaryReader br = new BinaryReader(fStream); 

    //When you use BinaryReader, you need to supply number of bytes to read from file. 
    //In this case we want to read entire file. So supplying total number of bytes. 
    data = br.ReadBytes((int)numBytes); 

    return data; 
} 

private void btnImage_Click(object sender, EventArgs e) 
{ 
    OpenFileDialog dlg = new OpenFileDialog(); 
    dlg.Filter = "JPG files (*.jpg)|*.jpg"; 
    DialogResult dlgRes = dlg.ShowDialog(); 
    if (dlgRes != DialogResult.Cancel) 
    { 
     pctImage.ImageLocation = dlg.FileName; 
     txtImage.Text = dlg.FileName; 
    } 
} 
+1

当进入跨越多行代码,您不使用反引号。您需要将每行缩进四个空格。 – Amy

+1

你会得到什么错误? – Fischermaen

+0

注意,如果你只读入一个字节数组,你不需要'BinaryReader'。您可以使用['FileStream.Read(byte []数组,int start,int count)](http://msdn.microsoft.com/zh-cn/library/system.io.filestream.read.aspx ) 方法。 – Amy

回答

0

那么它的从你发布的内容猜测,但你可能想看看有一个合适的文件来保存选定的测试。 浏览操作表明他们已经切换了floders并选择了一个。 只要打开对话框,如果他们没有点击文件(假设有一个文件),挖出图像将是一个无效的操作。