473,545 Members | 2,627 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

File corruption when retrieving files from a SQL 2005 database

Hello. I have an ASP.NET application (C#) that I allow users to
upload files. Files get stored in a SQL2005 database. The file data
is stored in a varbinary(max) column.

When the user uploads the file, I store it in a database. When a user
requests to download a file, the file is retrieved from the database
and then sent to them.

The files go in there ok. This is how I store them:

(note FileInfo is my own custom struct data type that I wrote to keep
track of File \ record info....NOT the System.IO class)

protected FileInfo StoreTempFile(F ileInfo fileInfo)
{
byte[] fileData;
Guid gFileID;
Stream stream;
HttpPostedFile postedFile;
Database db = DatabaseFactory .CreateDatabase ();

try
{
postedFile = this.FileUpload 1.PostedFile;
fileData = new byte[fileInfo.FileSi ze];
stream = postedFile.Inpu tStream;

stream.Read(fil eData, 0, fileInfo.FileSi ze);
stream.Close();

FileStream filestream = new FileStream("C:\ \test.txt",
FileMode.Create );
filestream.Writ e(fileData, 0, fileInfo.FileSi ze);
filestream.Clos e();

gFileID =
(Guid)db.Execut eScalar("Contra ctsFilesInsert" , fileInfo.Contra ctID,
fileInfo.FileNa me, fileInfo.FileSi ze, fileData, System.DateTime .Now);

fileInfo.FileID = gFileID;

return (fileInfo);
}
catch (Exception error)
{
return (fileInfo);
}
}

As you can see, I have some code to write the file to disk to double
check it's integrity (for debugging). The file gets uploaded fine and
is not corrupt before going into the database.
Here is the code used to retrieve the file from the database:
protected void SendFile(FileIn fo fileInfo)
{
Database db = DatabaseFactory .CreateDatabase ();
byte[] fileData = new byte[fileInfo.FileSi ze];

fileData =
(byte[])db.ExecuteScal ar("ContractsFi lesSelectByID", fileInfo.FileID );

FileStream filestream = new FileStream("C:\ \test.txt",
FileMode.Create );
filestream.Writ e(fileData, 0, fileInfo.FileSi ze);
filestream.Clos e();

Response.Flush( );
Response.ClearC ontent();
Response.ClearH eaders();
Response.Append Header("Content-Disposition", "attachment ;
filename=" + fileInfo.FileNa me);
Response.Conten tType = "text/plain";
Response.Binary Write(fileData) ;
Response.Flush( );
Response.End();
Response.Close( );
}
Here I am writing out the file to disk before I send the file out to
the user to double check it's integrity and eliminate the download
process as being the problem. The file that outputs is corrupt. Yes
I know the contentType will change according to the file...but I just
hardcoded "text/plain" temporarily as I am testing with text files.

Now...the odd part about all this, is JPG images seem to come out of
the database and sent to the downloader completely intact. Anything
else like zips, exe's, or even plain text files are corrupt.

Is the problem that I am using the ExecuteScaler method and casting
the results to a byte[]? If so, what's the preferred way to retrieve
files?

I'll be happy to include any additional information you need. Thanks
in advance!

Mar 26 '07 #1
5 2305
Anyone have any ideas? Or am I posting in an inappropriate group?
Mar 26 '07 #2
Have you tried ? :
- never catch an exception and do nothing. It could hide a problem in your
code.
- I would save both file and would start to compare their length ; if they
have the same length you can use the " fc" command to find out the first
mismatch. You can also use a well know pattern buffer (such as index mod 256
at offset "index"). It makes really easy to unit test you stream
reading/writing routine.

Good luck.

Patrice

<dj****@gmail.c oma écrit dans le message de news:
11************* *********@n59g2 00...legr oups.com...
Anyone have any ideas? Or am I posting in an inappropriate group?


Mar 26 '07 #3
execute scaler just return the first column of the the first row
returned from the query, so as long as this column is a varbinary you
should be ok.

check that the proc parameters are varbinary. also you use the saved
buffer size rather than the actual. executescaler is returnning a newly
allocated buffer, so there is no reason to allocate first.

hex dump a file and compare to the contents is sql as a hex string.

-- bruce (sqlwork.com)

dj****@gmail.co m wrote:
Hello. I have an ASP.NET application (C#) that I allow users to
upload files. Files get stored in a SQL2005 database. The file data
is stored in a varbinary(max) column.

When the user uploads the file, I store it in a database. When a user
requests to download a file, the file is retrieved from the database
and then sent to them.

The files go in there ok. This is how I store them:

(note FileInfo is my own custom struct data type that I wrote to keep
track of File \ record info....NOT the System.IO class)

protected FileInfo StoreTempFile(F ileInfo fileInfo)
{
byte[] fileData;
Guid gFileID;
Stream stream;
HttpPostedFile postedFile;
Database db = DatabaseFactory .CreateDatabase ();

try
{
postedFile = this.FileUpload 1.PostedFile;
fileData = new byte[fileInfo.FileSi ze];
stream = postedFile.Inpu tStream;

stream.Read(fil eData, 0, fileInfo.FileSi ze);
stream.Close();

FileStream filestream = new FileStream("C:\ \test.txt",
FileMode.Create );
filestream.Writ e(fileData, 0, fileInfo.FileSi ze);
filestream.Clos e();

gFileID =
(Guid)db.Execut eScalar("Contra ctsFilesInsert" , fileInfo.Contra ctID,
fileInfo.FileNa me, fileInfo.FileSi ze, fileData, System.DateTime .Now);

fileInfo.FileID = gFileID;

return (fileInfo);
}
catch (Exception error)
{
return (fileInfo);
}
}

As you can see, I have some code to write the file to disk to double
check it's integrity (for debugging). The file gets uploaded fine and
is not corrupt before going into the database.
Here is the code used to retrieve the file from the database:
protected void SendFile(FileIn fo fileInfo)
{
Database db = DatabaseFactory .CreateDatabase ();
byte[] fileData = new byte[fileInfo.FileSi ze];

fileData =
(byte[])db.ExecuteScal ar("ContractsFi lesSelectByID", fileInfo.FileID );

FileStream filestream = new FileStream("C:\ \test.txt",
FileMode.Create );
filestream.Writ e(fileData, 0, fileInfo.FileSi ze);
filestream.Clos e();

Response.Flush( );
Response.ClearC ontent();
Response.ClearH eaders();
Response.Append Header("Content-Disposition", "attachment ;
filename=" + fileInfo.FileNa me);
Response.Conten tType = "text/plain";
Response.Binary Write(fileData) ;
Response.Flush( );
Response.End();
Response.Close( );
}
Here I am writing out the file to disk before I send the file out to
the user to double check it's integrity and eliminate the download
process as being the problem. The file that outputs is corrupt. Yes
I know the contentType will change according to the file...but I just
hardcoded "text/plain" temporarily as I am testing with text files.

Now...the odd part about all this, is JPG images seem to come out of
the database and sent to the downloader completely intact. Anything
else like zips, exe's, or even plain text files are corrupt.

Is the problem that I am using the ExecuteScaler method and casting
the results to a byte[]? If so, what's the preferred way to retrieve
files?

I'll be happy to include any additional information you need. Thanks
in advance!
Mar 26 '07 #4
Here I've covered how to upload files into a SQL Server database and how to
successfully download them again to the client:
http://SteveOrr.net/articles/EasyUploads.aspx

--
I hope this helps,
Steve C. Orr,
MCSD, MVP, CSM, ASPInsider
http://SteveOrr.net
<dj****@gmail.c omwrote in message
news:11******** **************@ y80g2000hsf.goo glegroups.com.. .
Hello. I have an ASP.NET application (C#) that I allow users to
upload files. Files get stored in a SQL2005 database. The file data
is stored in a varbinary(max) column.

When the user uploads the file, I store it in a database. When a user
requests to download a file, the file is retrieved from the database
and then sent to them.

The files go in there ok. This is how I store them:

(note FileInfo is my own custom struct data type that I wrote to keep
track of File \ record info....NOT the System.IO class)

protected FileInfo StoreTempFile(F ileInfo fileInfo)
{
byte[] fileData;
Guid gFileID;
Stream stream;
HttpPostedFile postedFile;
Database db = DatabaseFactory .CreateDatabase ();

try
{
postedFile = this.FileUpload 1.PostedFile;
fileData = new byte[fileInfo.FileSi ze];
stream = postedFile.Inpu tStream;

stream.Read(fil eData, 0, fileInfo.FileSi ze);
stream.Close();

FileStream filestream = new FileStream("C:\ \test.txt",
FileMode.Create );
filestream.Writ e(fileData, 0, fileInfo.FileSi ze);
filestream.Clos e();

gFileID =
(Guid)db.Execut eScalar("Contra ctsFilesInsert" , fileInfo.Contra ctID,
fileInfo.FileNa me, fileInfo.FileSi ze, fileData, System.DateTime .Now);

fileInfo.FileID = gFileID;

return (fileInfo);
}
catch (Exception error)
{
return (fileInfo);
}
}

As you can see, I have some code to write the file to disk to double
check it's integrity (for debugging). The file gets uploaded fine and
is not corrupt before going into the database.
Here is the code used to retrieve the file from the database:
protected void SendFile(FileIn fo fileInfo)
{
Database db = DatabaseFactory .CreateDatabase ();
byte[] fileData = new byte[fileInfo.FileSi ze];

fileData =
(byte[])db.ExecuteScal ar("ContractsFi lesSelectByID", fileInfo.FileID );

FileStream filestream = new FileStream("C:\ \test.txt",
FileMode.Create );
filestream.Writ e(fileData, 0, fileInfo.FileSi ze);
filestream.Clos e();

Response.Flush( );
Response.ClearC ontent();
Response.ClearH eaders();
Response.Append Header("Content-Disposition", "attachment ;
filename=" + fileInfo.FileNa me);
Response.Conten tType = "text/plain";
Response.Binary Write(fileData) ;
Response.Flush( );
Response.End();
Response.Close( );
}
Here I am writing out the file to disk before I send the file out to
the user to double check it's integrity and eliminate the download
process as being the problem. The file that outputs is corrupt. Yes
I know the contentType will change according to the file...but I just
hardcoded "text/plain" temporarily as I am testing with text files.

Now...the odd part about all this, is JPG images seem to come out of
the database and sent to the downloader completely intact. Anything
else like zips, exe's, or even plain text files are corrupt.

Is the problem that I am using the ExecuteScaler method and casting
the results to a byte[]? If so, what's the preferred way to retrieve
files?

I'll be happy to include any additional information you need. Thanks
in advance!
Mar 27 '07 #5
hahaha! I figured out the problem. The problem wasn't in the code at
all, but in my stored procedure.

Basically, in the stored procedure I was doing a Select File_Data
>From Table_Name Where @File_ID = @File_ID. Note the @ symbol in
front of the column name! Bad! So, the end result was a query that
always returned the data for the first record in the table. Not
corrupt data....but the WRONG data. lol.

Thanks for the help!

Mar 27 '07 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
1946
by: Fred MacMurray | last post by:
Hello, all. So we're all happy with Access. Or Access is "good enough" with most of our applications. I built a split database here at work that has about seven users who are on pretty much the entire workday. The backend is on the server with each client having a frontend. I've spent the past couple days researching corruption because...
5
2109
by: Upendra Agnihotram | last post by:
Hi, I am having Client-Server Access application. The source db resides on WinNT Server and some of the client systems are on Windows 2000 Professional. These days i am experiencing frequent corruption of the source database (nearly 3 to 4 times a day) which is on NT Machine?. Please let me know if there is any solution for this ...
9
15741
by: John | last post by:
Hi All, I have encountered a problem with the ldb file of a database. When making changes to the backend databases I need exclusive access to make changes. I usually do this at night when all users have left the premises, but for the last couple of nights there are no users using the database and the ldb file is still visible even though...
3
1418
by: Scott | last post by:
Hi anyone!!! I have an access database file which is corupted after a computer crash. I have tried a compact and repair which failed. I have purchased an Access Repair package which can only find 3 out of the 40 tables. When I try to open the files I receive an eroor message saying "Tables.mdb"
2
1333
by: Tom van Stiphout | last post by:
Hi all, I have a fairly large Access2000 application (FE/BE). One of the subforms (in datasheet) has a dropdown list named BackSplash. It's a ValueList, not LimitToList, bound to the BackSplash field in the underlying query. The subform also (among various other fields) has a textbox named LineItemPrice. This is the last field in the...
4
5138
by: Brian K. | last post by:
I am trying to split up and secure a database that we've been using on a network for a few years, following the procedure listed in Q304932 from microsoft. I create a new blank database for the front end, and am able to import tables and link from the backend. Queries come in ok too. When I tried to import Modules, forms, and reports,...
13
9482
by: Bob Darlington | last post by:
I have a repair and backup database routine which runs when a user closes down my application. It works fine in my development machine, but breaks on a client's at the following line: If Dir(strLDB) <> "" Then Kill (strLDB) where strLDB is the path to the ldb file. The client advises that the ldb doesn't lurk after the program closes. Any...
2
1750
by: nepdae | last post by:
Please forgive me, this is a long one. My 11-user Access 2000 database is having recurring corruption problems. The symptoms include the following: 1) corrupted fields in recently created or accessed records 2) incorrectly linked records via primary and foreign keys (looking at the tables displays the correct key number but when filtered...
3
22264
by: Stephan | last post by:
Hi all, I am new to access and I face the following "issue": I would like to create a database, to which users can upload files (=pdf, doc, xls...). The files shall be stored locally on a server. The database needs to be accessed via Access form (no html, asp,...) as we don't have an internal web server running. I would like to create a...
0
7941
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7452
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6014
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5354
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5071
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3485
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3467
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1916
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
738
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.