我正在使用C#windows窗體應用程序將文件上載到SQL Server,但用戶不會總是上傳文件,如果用戶直接按下保存而不使用OpenFileDialog
應該保存在空數據庫即使表列設置爲「允許null」,也無法保存數據庫中的空值
我保存按鈕的代碼是
private void btnSave_Click(object sender, EventArgs e)
{
try
{
//Read File Bytes into a byte array for attaching file
byte[] FileData = ReadFile(txtpath.Text);
con.Open();
cmd = new SqlCommand("insert into CourierMaster(srno,OriginalPath,FileData)values(" + txtsrNo.Text + ",@OriginalPath, @FileData)", con);
cmd.Parameters.Add(new SqlParameter("@OriginalPath", (object)txtpath.Text));
cmd.Parameters.Add(new SqlParameter("@FileData", (object)FileData));
int n = cmd.ExecuteNonQuery();
if (n > 0)
{
MessageBox.Show("Record for "+txtsrNo.Text+" Inserted Successfully.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
MessageBox.Show("Insertion failed");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
我READFILE()函數是
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);
//Close BinaryReader
br.Close();
//Close FileStream
fStream.Close();
return data;
}
我得到è RROR
「的路徑是不是合法的形式。」
在我的ReadFile()函數錯誤發生在這個FileInfo fInfo = new FileInfo(sPath);
行代碼,我知道我們不能空分配給路徑,但這是否意味着如果它是一個路徑,我不能在我的數據庫中保存空值?
以下是我的應用程序的快照:
以下是我的表扣:
當您從ReadFile中得到錯誤時,爲什麼您會懷疑數據庫是根本原因?我希望'sPath'無效。檢查它包含的內容。 – usr
調試時sPath包含一個空值,即「」 –