Hello,
I am able to extract each line and save into database from a .txt file, but it is only saving 1000 lines, is there a way to save all the lines if they are more than 15,000 lines?
protected void Button1_Click(object sender, EventArgs e)
{
try
{
if (!FileUpload1.HasFile) //Validation
{
Response.Write("No file Selected"); return;
}
else
{
// Read and Extract Information from the Index.txt File:
string path = ConfigurationManager.AppSettings["ImageBasePath"];
var files = Directory.GetFiles(path, "index.txt", SearchOption.AllDirectories);
// Read and populate textboxes from Index.txt
string filePath = Path.Combine(files);
var lines = File.ReadAllLines(Path.Combine(filePath));
//var lines = File.ReadAllLines(filePath);
foreach (var line in lines)
{
var parts = line.Split('|');
if (parts.Length >= 9)
{
// Extract required information
string acctNumber = parts[0];
string chkNumber = parts[1];
string chkAmount = parts[2];
string imgDate = parts[5];
string imagePath = parts[8];
// Populate the textboxes
txtAcctNumber.Text = acctNumber.ToString();
txtChkNumber.Text = chkNumber.ToString();
txtChkAmount.Text = chkAmount.ToString();
txtDate.Text = imgDate;
//Optional, store the imagePath if needed
ViewState["ImagePath"] = imagePath;
// break; // Remove this if you want to handle multiple lines
}
// Extract values from textboxes
string acctNumbers = txtAcctNumber.Text;
string chkNumbers = txtChkNumber.Text;
string chksAmount = txtChkAmount.Text;
string imgDates = txtDate.Text;
string imagePaths = ViewState["ImagePath"].ToString();
// Retrieve the base path from the configuration
string basePath = ConfigurationManager.AppSettings["ImageBasePath"];
// Construct the full path to the image file
string fullImagePath = Path.Combine(basePath, imagePaths);
// Convert the image to byte array
byte[] imageData = File.ReadAllBytes(fullImagePath);
//string imageBase64 = Convert.ToBase64String(imageData);
//Console.WriteLine(imageBase64);
// Insert the data into the database
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCU"].ToString()))
{
connection.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO chkImages (acctNumber, chkNumber,chkAmount, imgDate, imageData) VALUES (@acctNumber, @chkNumber, @chkAmount, @imgDate, @imageData)", connection);
cmd.Parameters.AddWithValue("@acctNumber", acctNumbers);
cmd.Parameters.AddWithValue("@chkNumber", chkNumbers);
cmd.Parameters.AddWithValue("@chkAmount", chksAmount);
cmd.Parameters.AddWithValue("@imgDate", imgDates);
cmd.Parameters.AddWithValue("@imageData", imageData);
cmd.ExecuteNonQuery();
connection.Close();
Response.Write("Image has been Added");
}
}
}
}
catch (Exception ex)
{
// Handle any exceptions that occurred
Console.WriteLine("An error occurred while reading the file: " + ex.Message);
}
}
Nikunj SatasiyaPosted Jul 23, 2024, 6:29 AM
Ivonne, It looks like your code is designed to read all lines from the file and process each line individually. The issue with only 1000 lines being saved could be due to several reasons. Here are some things you can check and modify to ensure all lines are processed:
1. Check for Errors in the Data
Ensure that all the lines in your .txt file follow the expected format, especially since your code processes lines based on a specific structure (splitting by | and expecting at least 9 parts). Lines that do not meet this condition will be skipped.
2. Database Transaction and Commit Size
If the database transaction is too large, it might be causing timeouts or memory issues. You can implement batch processing or use transactions to commit data in chunks.
3. Increase the Timeout
Check if your database connection or command timeout is set too low, which might be stopping the process prematurely.
4. Optimize the Code
Your current code is reading and processing the file line by line inside a loop where each line triggers database operations. This can be optimized.
Optimized Code:
You could modify your code to use a batch insert approach, where you collect a batch of data and insert it all at once, reducing the number of round-trips to the database. Here’s an example of how you could modify your loop:
By optimizing the code and ensuring that the database operations are efficiently handled, you should be able to process a larger number of lines without issues. Ensure that the server handling the requests has enough resources (RAM, CPU) to handle large operations if the file sizes are very large. Also, consider the network and disk I/O if the database server is separate from the application server.
Amit MohantyPosted Jul 23, 2024, 5:36 AM
I think the issue might be due to a limitation in the database. Try the below code once:
Mayooran NavamanyPosted Jul 23, 2024, 4:23 AM
Hi
Batch Processing: Instead of inserting one line at a time, you can use batch processing to insert multiple lines in a single database transaction. This reduces the number of database calls and improves performance.
Async/Await: Utilize asynchronous programming to prevent blocking operations, especially when dealing with large files and database operations.
Error Handling: Enhance error handling to manage failures gracefully.
Here is an improved version of your code that incorporates these suggestions:
Key Improvements:Batch Processing: The
InsertRecordsAsyncmethod processes a list of records, which can be further optimized for batch insertions if your database supports it.Asynchronous Operations: Used asynchronous methods (
ReadAllLinesAsync,ReadAllBytesAsync,OpenAsync,ExecuteNonQueryAsync) to prevent blocking operations.Separation of Concerns: Extracted the database insertion logic into a separate method
InsertRecordsAsyncfor better code organization and readability.Enhanced Error Handling: Added exception handling for database operations separately to catch and log any issues specifically related to database operations.