あなたはどのようなタイプのファイルを格納するためにVARBINARY(MAX)
を使用することができます。私は自分自身であなたに例を与えている
、それが役に立てば幸い。
まず、2つの列を追加(ファイル名VARCHAR(20)を、含むFileContent VARBINARY(MAX))以下
が挿入および取り出しのためのサンプルCSコードである(例えばtblSampleImage)テーブルを作成しますデータベースからファイル:
public void insertFile()
{
string fileName= Path.GetFileName(@"your file full path");
string filePath= Path.GetFullPath(@"your file full path");
if (!File.Exists(filePath))
{
MessageBox.Show("File not found");
return;
}
byte[] contents= File.ReadAllBytes(filePath);
string insertStmt = "INSERT INTO tblSampleImage(FileName, FileContent) VALUES(@FileName, @FileContent)";
SqlConnection connection = new SqlConnection();
connection.ConnectionString = "connectionString";
using (SqlCommand cmdInsert = new SqlCommand(insertStmt, connection))
{
cmdInsert.Parameters.Add("@FileName", SqlDbType.VarChar, 20).Value = fileName;
cmdInsert.Parameters.Add("@FileContent", SqlDbType.VarBinary, int.MaxValue).Value = contents;
connection.Open();
cmdInsert.ExecuteNonQuery();
connection.Close();
}
}
ファイル
を取得するために
public void fetchFile()
{
string newFilePath = Path.GetFullPath(@"your new path where you store your fetched file");
string fileName="File1"; //this is the file's name which is stored in database and you want to fetch
byte[] fileContents;
string selectStmt = "SELECT FileContent FROM tblSampleImage WHERE FileName = @FileName";
SqlConnection connection = new SqlConnection();
connection.ConnectionString = "connectionString";
using (SqlCommand cmdSelect = new SqlCommand(selectStmt, connection))
{
cmdSelect.Parameters.Add("@Filename", SqlDbType.VarChar).Value = fileName;
connection.Open();
fileContents = (byte[])cmdSelect.ExecuteScalar();
connection.Close();
}
File.WriteAllBytes(newFilePath, fileContents);
MessageBox.Show("File Saved at: " + newFilePath);
}
*** ***データベースは何ですか?これは、あなたが話している具体的なデータベースシステムに大きく依存しています...... –
@marc_s SQl Serverデータベースの列データ型はimageです。 – Shahbaz
'ntext'、' text'、および 'image'データ型は、将来のバージョンのSQL Serverでは削除されます。新しい開発作業でこれらのデータ型を使用しないようにし、現在使用しているアプリケーションを変更することを計画します。代わりに 'nvarchar(max)'、 'varchar(max)'、 'varbinary(max)'を使用してください。 [詳細を見る](http://msdn.microsoft.com/en-us/library/ms187993.aspx) –