2011-11-26 67 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並選擇了一個。 只要打開對話框,如果他們沒有點擊文件(假設有一個文件),挖出圖像將是一個無效的操作。