我正在使用 ASP.Net MVC-web 应用程序中的上传页面将二进制文件/附件存储在 Postgress 数据库中。如果我在控制台程序中获取这些附件并将内容写入磁盘,所有附件都很好,我可以读取它们。如果我在我的 Web 应用程序中执行完全相同的代码,则每个附件的内容都会损坏。这是什么原因造成的?
这是我正在使用的代码:
private void DumpBijlagen( )
{
NpgsqlConnection connection = null;
try
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
string connectionString = "Server=127.0.0.1;Port=5432;User Id=gtsys;Password=gtsys;Database=postgis20";
connection = new NpgsqlConnection( connectionString);
StringBuilder sb = new System.Text.StringBuilder( );
sb.AppendFormat( "select id, filename, filesize, created, data from web_bijlagen" );
string sql = sb.ToString( );
d.WriteLine( sql);
NpgsqlDataAdapter da = new NpgsqlDataAdapter( sql, connection);
da.Fill( ds);
dt = ds.Tables[ 0];
string filename = string.Empty;
int fileSize = 0;
byte[] bytes = null;
foreach( DataRow dr in dt.Rows)
{
filename = System.Convert.ToString ( dr[ "filename"]);
fileSize = System.Convert.ToInt32 ( dr[ "filesize"]);
bytes = dr[ "data"] as byte[];
WriteBijlage( filename, bytes);
}
DataDumper.Dump( dt);
connection.Close();
}
catch( System.Exception ex)
{
d.WriteLine( ex.Message);
}
finally
{
if( connection.State == System.Data.ConnectionState.Open)
{
connection.Close( );
}
}
}
private void WriteBijlage( string filename, byte[] bytes)
{
filename = string.Format( @"d:\Usr\Stephan\Junk\wBijlagen\{0}", filename);
FileStream fs = new FileStream ( filename, FileMode.Create, FileAccess.Write);
BinaryWriter bw = new BinaryWriter ( new BufferedStream(fs));
bw.Write( bytes);
bw.Flush();
fs.Close();
bw.Close();
}