问题是当我下载文件时,我可以在下载文件中看到路径。我没有得到文件的实际内容。
当我附加名为sample.txt且的文件时,sample.txt的路径为== C:\Users\smohan\Downloads\databse\LocalDataBaseAp\sample.txt
。我可以看到路径与我的数据网格绑定。但是当我单击网格的单元格并下载相同的文件时。该文件正在下载。但是当我打开..我在里面看到的下载文件缺少实际内容,而是将路径保存为内容(即) C:\ Users \ smohan \ Downloads \ database \ LocalDataBaseAp \ sample.txt < /强>
我的代码出了什么问题?
private void UploadAttachment(DataGridViewCell dgvCell)
{
using (OpenFileDialog fileDialog = new OpenFileDialog())
{
//Set File dialog properties
fileDialog.CheckFileExists = true;
fileDialog.CheckPathExists = true;
fileDialog.Filter = "All Files|*.*";
fileDialog.Title = "Select a file";
fileDialog.Multiselect = true;
if (fileDialog.ShowDialog() == DialogResult.OK)
{
cncInfoDataGridView.Rows[dgvCell.RowIndex].Cells[1].Value = fileDialog.FileName;
SqlCeConnection cnn = new SqlCeConnection(Properties.Settings.Default.CncConnectionString);
//FileInfo fileInfo = new FileInfo(fileDialog.FileName);
byte[] imgData;
imgData = File.ReadAllBytes(fileDialog.FileName);}
}
}
/// <summary>
/// Download Attachment from the provided DataGridViewCell
/// </summary>
/// <param name="dgvCell"></param>
private void DownloadAttachment(DataGridViewCell dgvCell)
{
string strId = cncInfoDataGridView.Rows[dgvCell.RowIndex].Cells[1].Value.ToString();
string fileName = Convert.ToString(dgvCell.Value);
if (!string.IsNullOrEmpty(fileName))
{
byte[] objData;
FileInfo fileInfo = new FileInfo(fileName);
string fileExtension = fileInfo.Extension;
//show save as dialog
using (SaveFileDialog saveFileDialog1 = new SaveFileDialog())
{
//Set Save dialog properties
saveFileDialog1.Filter = "Files (*" + fileExtension + ")|*" + fileExtension;
saveFileDialog1.Title = "Save File as";
saveFileDialog1.CheckPathExists = true;
saveFileDialog1.FileName = fileName;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string s = cncInfoDataGridView.Rows[dgvCell.RowIndex].Cells[1].Value.ToString();
objData = System.Text.Encoding.ASCII.GetBytes(s);
string strFileToSave = saveFileDialog1.FileName;
File.WriteAllBytes(saveFileDialog1.FileName, objData);
}
}
}
}
}
}
答案 0 :(得分:1)
我明白你现在正在做什么;所以,这里是相关的代码部分:
objData = System.Text.Encoding.ASCII.GetBytes(s);
问题是我认为你误解了System.Text.Encoding.ASCII.GetBytes(string)
的作用。它不读取文件的内容;它会对您传递给它的字符串进行编码。因此,您正在从Grid中编写文件路径 - 而不是文件的内容。这更像你想要的:
objData = File.ReadAllBytes(s);
它会读取您传递给它的路径中文件的所有字节,并返回byte[]
,就像您使用的那样。