faster method to import data from text file - c#

I have to import data from a text file to a flat file database. I'm sure there's a faster way to load all the data into the database but I don't know how.
private void ImportButton_Click(object sender, EventArgs e)
{
string Path = string.Empty;
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Text File|*.txt";
ofd.ShowDialog();
if (ofd.FileName == string.Empty) return
Path = ofd.FileName;
string data;
using (var sr = new StreamReader(Path))
{
data = sr.ReadToEnd();
}
var items = data.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
var count = 0;
foreach (var info in items.Select(ItemInfo.FromText).Where(info => info != null))
{
count++;
info.Index = ++Envir.ItemIndex;
Envir.ItemInfoList.Add(info);
}
MessageBox.Show(count + " Items have been imported");
UpdateInterface(true);
}

If you're doing this via C#, then I'd recommend SqlBulkCopy. I provided a similar answer to another question a while back. See that link for an example of how I've implemented it in the past.
If you want to know other options available to you then MSDN has quite a good list of options in their data loading guide; http://msdn.microsoft.com/en-us/library/dd425070(v=sql.100).aspx

Related

How to link users file selection to a StringSplit

I'm trying to get the users chosen file to split into an array which is separated by , and /t.
The user can choose a file at the top of the code but how do I get their choice to split into an array lower down when they press the ValidateButton
The text file or ordered in this way
info,info,info,
info,info,info,
info,info,info,
If I can get them into an array then I can easily organises the data.
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = #"C:\"; // Start in C: drive
openFileDialog1.Title = "Browse Text Files";
openFileDialog1.RestoreDirectory = true;
openFileDialog1.DefaultExt = "txt"; // Extension of file is txt
openFileDialog1.Filter = "Text|*.txt||*.*"; //Only text files
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
FileNameBox.Text = openFileDialog1.FileName; // Chosen file name is displayed in text box
var fileStream = openFileDialog1.OpenFile();
using (StreamReader reader = new StreamReader(fileStream))
{
var fileContent = reader.ReadToEnd();
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
//This is the file path the user has chosen
}
public void ValidateButton_Click(object sender, EventArgs e)
{
//Call Multi line text box
//Call PROGRESS BAR_
int counter = 0;
string lines;
string Patient = lines;
string[] split = Patient.Split(new Char[] { ',', '\t' });
foreach (string s in split)
if (s.Trim() != "")
Console.WriteLine(s);
{
Console.WriteLine(lines);
counter++;
}
Console.WriteLine("There were {0} records.", counter);
Console.ReadKey();
}
List<string> temp = new List<string>();
string[] finalArray;
using (StreamReader reader = new StreamReader(fileStream))
{
// We read the file then we split it.
string lines = reader.ReadToEnd();
string[] splittedArray = lines.Split(',');
// We will check here if any of the strings is empty (or just whitespace).
foreach (string currentString in splittedArray)
{
if (currentString.Trim() != "")
{
// If the string is not empty then we add to our temporary list.
temp.Add(currentString);
}
}
// We have our splitted strings in temp List.
// If you need an array instead of List, you can use ToArray().
finalArray = temp.ToArray();
}

Save Opened Text File to Original Location

I am creating an application that will allow me to open a .txt file and edit the values (weight=60, height =50, etc) in a DataGridView. My issue is that I am able to upload the .txt file using OpenFileDialog but am unable to write over and save it in it's previous location.
For clarification, here is my method to upload text files:
private void btnUpload_Click(object sender, EventArgs e)
{
Stream myStream;
openFileDialog1.FileName = string.Empty;
openFileDialog1.InitialDirectory = "C:\\";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
var compareType = StringComparison.InvariantCultureIgnoreCase;
var fileName = Path.GetFileNameWithoutExtension(openFileDialog1.FileName);
var extension = Path.GetExtension(openFileDialog1.FileName);
if (extension.Equals(".txt", compareType))
{
try
{
using (myStream = openFileDialog1.OpenFile())
{
string file = Path.GetFileName(openFileDialog1.FileName);
string path = Path.GetDirectoryName(openFileDialog1.FileName);
StreamReader reader = new StreamReader(openFileDialog1.FileName);
string line;
while ((line = reader.ReadLine()) != null)
{
string[] words = line.Split('=');
paramList.Add(new Parameter(words[0], words[1]));
}
BindGrid();
}
}
And what I've tried to save the file:
public void WriteToTextFile(DataGridView dgvParam)
{
String file_name = Path.GetFileNameWithoutExtension(openFileDialog1.FileName);
using (StreamWriter objWriter = new StreamWriter(openFileDialog1.FileName))
{
for (Int32 row = 0; row < dgvParam.Rows.Count - 1; row++)
{
StringBuilder sb = new StringBuilder();
for (Int32 col = 0; col < dgvParam.Rows[row].Cells.Count; col++)
{
if (!String.IsNullOrEmpty(sb.ToString()))
sb.Append("="); //any delimiter you choose
sb.Append(dgvParam.Rows[row].Cells[col].Value.ToString().ToUpper());
}
objWriter.WriteLine(sb.ToString());
}
}
It says it is openFileDialog is currently in use and it cannot reach it! Any suggestions or recommendations would be really appreciated!
You need to dispose your reader variable.
You should get rid of the first using statement entirely and wrap that in a using statement instead.

Importing file to array

I want the user to be able to chose a text file written in a certain way (1 number per line) and then have the file converted into an array. I have bits and pieces of it working but I cant get it to all work at the same time. Any help would be appreciated.
private void Load_Button_Click(object sender, EventArgs e)
{
int counter = 0;
string line;
List<int> list = new List<int>();
string fileName = "";
//OpenFileDialog ofd = new OpenFileDialog();
//ofd.Filter = "TXT File|*.txt";
//ofd.Title = "Open File";
// if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
// {
File_Label.Text = "C:/Users/Neilan/Desktop/sample.txt";
//fileName = "#" + ofd.SafeFileName;
//MessageBox.Show(ofd.FileName);
System.IO.StreamReader file = new System.IO.StreamReader(#"C:\Users\Neilan\Desktop\sample.txt");
while ((line = file.ReadLine()) != null)
{
Unsorted_Box.Text += line + ", ";
//list.Add(int.Parse(fileName));
counter++;
}
dataArray = list.ToArray();
// }
}
You can do this.
var numberarray = File.ReadAllLines("stringpath").Select(int.Parse).ToArray();
Looking at your code, I guess you want to show these values in comma separated format to user. You can achieve this with following code snippet.
Unsorted_Box.Text = String.Join(",", numberarray.ToArray());
Hope this helps !
This problem can be solved by one line
var resultArray = Array.ConvertAll(System.IO.File.ReadAllLines("filename.type"), str => int.Parse(str));
Instead of "filename.type" you can put something like File_Label.Text

How do I check if one of the lines already exist in the text file?

string filename = "";
private void openToolStripMenuItem1_Click(object sender, EventArgs e)
{
OpenFileDialog theDialog = new OpenFileDialog();
theDialog.Title = "Open Text File";
theDialog.Filter = "TXT files|*.txt";
theDialog.InitialDirectory = #"C:\";
if (theDialog.ShowDialog() == DialogResult.OK)
{
lines = File.ReadAllLines(RecentFiles);
filename = theDialog.FileName;
for (int i = 0; i < lines.Length; i++)
{
recentfiles = new StreamWriter(RecentFiles, true);
recentfiles.WriteLine(theDialog.FileName);
recentfiles.Close();
items = File
.ReadLines(RecentFiles)
.Select(line => new ToolStripMenuItem()
{
Text = line
})
.ToArray();
recentFilesToolStripMenuItem.DropDownItems.AddRange(items);
}
TextFileContentToRichtextbox(filename);
}
}
I'm not sure if doing the for loop over the lines is right.
But what I want to do is when I open a new text file to check if it already exists in the RecentFiles(RecentFiles.txt) and if it does exist don't write it again.
Loop over lines and if after looping over all the lines and the variable filename does not exist then write it to the text file, and update the items.
Linq is perfect for this:
// if there are not any lines that equal the filename
if (!lines.Any(line => line.Equals(filename)))
{
// then write it into recent files text file
}
//// the below code will work only if a line has 1 fileName with extension or any text.
if (lines.Contains(filename, StringComparer.OrdinalIgnoreCase))
{
//// lines contains
}
else
{
////lines doesnot contain file name
}
Verify whether it full fill your requirement.

EPPlus To Read 1st Column Of Excel Into Array

Use OpenFileDialogwith EPPlus. I get a compile error of:
The name 'sheet' does not exist in the current context
Now, the obvious issue is how do I associate the selected Excel file with my EPPPlus & 2 what do I do to remove the error above?
using OfficeOpenXml;
using OfficeOpenXml.Drawing;
private void btn_ReadExcelToArray_Click(object sender, EventArgs e)
{
fd.Filter = "Excel Files|*.xlsx";
fd.InitialDirectory = #"C:\";
if (fd.ShowDialog() == DialogResult.OK)
{
var columnimport = sheet.Cells["A2:A"];
foreach (var cell in columnimport)
{
var column1CellValue = cell.GetValue<string>();
}
}
}
You are pretty close. All you have to do is create the package based on the stream (or you could use the fileinfo overload - either way). Like this:
var fd = new OpenFileDialog();
fd.Filter = "Excel Files|*.xlsx";
fd.InitialDirectory = #"C:\Temp\";
if (fd.ShowDialog() == DialogResult.OK)
{
using (var package = new ExcelPackage(fd.OpenFile()))
{
var sheet = package.Workbook.Worksheets.First();
var columnimport = sheet.Cells["A2:A"];
foreach (var cell in columnimport)
{
var column1CellValue = cell.GetValue<string>();
}
}
}

Categories

Resources