Import text file content to the SQL Server database in Asp.net

Source: Internet
Author: User
Tags bulk insert
For example:

Show notepad content

Show database fields

InProgram(Select "Upload File" and click "Upload". The file location is displayed in the text box. Click "publish" to publish the notepad data to the database ):

Upload button Code :

 

View code String Name, FL;
Name = This . Txt. text;

String Filename =   "" ;
If (File1.postedfile. contentlength ! =   0 )
{
String FN = File1.postedfile. filename;
Filename = Getrandomfilename ();
Filename + = FN. substring (fn. lastindexof ( " . " ));
If (Fn. substring (fn. lastindexof ( " . " ) +   1 ). Tolower () =   " Txt " ))
{
If (File1.postedfile. contentlength >   25000000 )
{
Response. Write ( " <SCRIPT> alert ('do not upload files larger than 25 MB! ') </SCRIPT> " );
}
Else
{
File1.postedfile. saveas (server. mappath ( " ~ /Txt " ) +   " / "   + Filename );
}
}
Else
{
Response. Write ( " <SCRIPT> alert (' "   + FN. substring (fn. lastindexof ( " . " ) +   1 ). Tolower () +   " Select a file in the format of "TXT") </SCRIPT> " );
Return ;
}

}
FL= "TXT \\" +Filename;
This. Txt. Text=FL;

 

Code for naming notepad file names:

 

View code Static   Public   String Getrandomfilename ()
{
System. Random Rand =   New System. Random ();
Datetime now = Datetime. now;
String Str =   "" ;
Str + = Now. year. tostring ();
Str + = Now. Month. tostring ();
Str + = Now. Day. tostring ();
Str + = Now. Hour. tostring ();
Str + = Now. Minute. tostring ();
Str + = Now. Second. tostring ();
Str + = Rand. Next ( 0 , 1000 );
Return STR;

}

Code for publishing data to a database:

string f0 = This. TXT. text;
string F = "E: \ edt_manager \" + F0; // obtain the file storage path
string SQL = "BULK INSERT txt_table from '" + F + "' with (fieldterminator = ',', rowterminator = '\ n ') "; // insert data
EDT. exesql (SQL);

EDT is a class file and connects to the database. The above can be implemented.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.