I watch a lot of tutorials on how to delete a certain row in Excel.
Please help mo to delete a row in excel using c#.
The fileReader ,FileWriter and Splitter are already working. My only problem now is how to delete a certain row in Excel.
Class Variable
public static string fileName = #".\Contestant.csv";
public static string[,] contestant;
Main Method
List<string> lines = fileReader(fileName);
while (i < lines.Count)
{
string[] temp = stringSplitter(lines[i], new char[] { ',' });
// a contains how many elements in the array
a = temp.Count();
// divides a and plus by 1 to know how many arrays there should be in the 2d array
d = (a / 2) + 1;
contestant = new string[a, d];
This is my code for FileReader
static List<string> fileReader(string filePath)
{
List<string> lines = new List<string>();
try
{
using (StreamReader sr = new StreamReader(filePath))
{
string line = "";
while ((line = sr.ReadLine()) != null)
{
lines.Add(line);
}
}
}
catch (Exception e)
{
Console.WriteLine("Error Message: Please close the file and try again");
//Console.WriteLine(e); for more detailed errors
}
return lines;
}
Here's my code for FileWriter
static void fileWriter(string filePath, bool appendFlag, string message)
{
using (StreamWriter sr = new StreamWriter(filePath, appendFlag))
{
sr.WriteLine(message);
}
}
This is for Splitter String
static string[] stringSplitter(string stringToSplit, char[] splitChars)
{
return stringToSplit.Split(splitChars);
}
I would recommend to completely manipulate your date inside the lists, then replace the whole document with the new information. So read all -> manipulate -> replace your document with new content.
Also don't forget to close your FileStreams after reading/writing.
I am trying to write into a csv file row by row using C# language. Here is my function
string first = reader[0].ToString();
string second=image.ToString();
string csv = string.Format("{0},{1}\n", first, second);
File.WriteAllText(filePath, csv);
The whole function runs inside a loop, and every row should be written to the csv file. In my case, next row overwrites the existing row and in the end, I am getting an only single record in the csv file which is the last one. How can I write all the rows in the csv file?
UPDATE
Back in my naïve days, I suggested doing this manually (it was a simple solution to a simple question), however due to this becoming more and more popular, I'd recommend using the library CsvHelper that does all the safety checks, etc.
CSV is way more complicated than what the question/answer suggests.
Original Answer
As you already have a loop, consider doing it like this:
//before your loop
var csv = new StringBuilder();
//in your loop
var first = reader[0].ToString();
var second = image.ToString();
//Suggestion made by KyleMit
var newLine = string.Format("{0},{1}", first, second);
csv.AppendLine(newLine);
//after your loop
File.WriteAllText(filePath, csv.ToString());
Or something to this effect.
My reasoning is: you won't be need to write to the file for every item, you will only be opening the stream once and then writing to it.
You can replace
File.WriteAllText(filePath, csv.ToString());
with
File.AppendAllText(filePath, csv.ToString());
if you want to keep previous versions of csv in the same file
C# 6
If you are using c# 6.0 then you can do the following
var newLine = $"{first},{second}"
EDIT
Here is a link to a question that explains what Environment.NewLine does.
I would highly recommend you to go the more tedious route. Especially if your file size is large.
using(var w = new StreamWriter(path))
{
for( /* your loop */)
{
var first = yourFnToGetFirst();
var second = yourFnToGetSecond();
var line = string.Format("{0},{1}", first, second);
w.WriteLine(line);
w.Flush();
}
}
File.AppendAllText() opens a new file, writes the content and then closes the file. Opening files is a much resource-heavy operation, than writing data into open stream. Opening\closing a file inside a loop will cause performance drop.
The approach suggested by Johan solves that problem by storing all the output in memory and then writing it once. However (in case of big files) you program will consume a large amount of RAM and even crash with OutOfMemoryException
Another advantage of my solution is that you can implement pausing\resuming by saving current position in input data.
upd. Placed using in the right place
Writing csv files by hand can be difficult because your data might contain commas and newlines. I suggest you use an existing library instead.
This question mentions a few options.
Are there any CSV readers/writer libraries in C#?
I use a two parse solution as it's very easy to maintain
// Prepare the values
var allLines = (from trade in proposedTrades
select new object[]
{
trade.TradeType.ToString(),
trade.AccountReference,
trade.SecurityCodeType.ToString(),
trade.SecurityCode,
trade.ClientReference,
trade.TradeCurrency,
trade.AmountDenomination.ToString(),
trade.Amount,
trade.Units,
trade.Percentage,
trade.SettlementCurrency,
trade.FOP,
trade.ClientSettlementAccount,
string.Format("\"{0}\"", trade.Notes),
}).ToList();
// Build the file content
var csv = new StringBuilder();
allLines.ForEach(line =>
{
csv.AppendLine(string.Join(",", line));
});
File.WriteAllText(filePath, csv.ToString());
Instead of calling every time AppendAllText() you could think about opening the file once and then write the whole content once:
var file = #"C:\myOutput.csv";
using (var stream = File.CreateText(file))
{
for (int i = 0; i < reader.Count(); i++)
{
string first = reader[i].ToString();
string second = image.ToString();
string csvRow = string.Format("{0},{1}", first, second);
stream.WriteLine(csvRow);
}
}
You can use AppendAllText instead:
File.AppendAllText(filePath, csv);
As the documentation of WriteAllText says:
If the target file already exists, it is overwritten
Also, note that your current code is not using proper new lines, for example in Notepad you'll see it all as one long line. Change the code to this to have proper new lines:
string csv = string.Format("{0},{1}{2}", first, image, Environment.NewLine);
Instead of reinventing the wheel a library could be used. CsvHelper is great for creating and reading csv files. It's read and write operations are stream based and therefore also support operations with a big amount of data.
You can write your csv like the following.
using(var textWriter = new StreamWriter(#"C:\mypath\myfile.csv"))
{
var writer = new CsvWriter(textWriter, CultureInfo.InvariantCulture);
writer.Configuration.Delimiter = ",";
foreach (var item in list)
{
writer.WriteField( "a" );
writer.WriteField( 2 );
writer.WriteField( true );
writer.NextRecord();
}
}
As the library is using reflection it will take any type and parse it directly.
public class CsvRow
{
public string Column1 { get; set; }
public bool Column2 { get; set; }
public CsvRow(string column1, bool column2)
{
Column1 = column1;
Column2 = column2;
}
}
IEnumerable<CsvRow> rows = new [] {
new CsvRow("value1", true),
new CsvRow("value2", false)
};
using(var textWriter = new StreamWriter(#"C:\mypath\myfile.csv")
{
var writer = new CsvWriter(textWriter, CultureInfo.InvariantCulture);
writer.Configuration.Delimiter = ",";
writer.WriteRecords(rows);
}
value1,true
value2,false
If you want to read more about the librarys configurations and possibilities you can do so here.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
public partial class CS : System.Web.UI.Page
{
protected void ExportCSV(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Customers"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
//Build the CSV file data as a Comma separated string.
string csv = string.Empty;
foreach (DataColumn column in dt.Columns)
{
//Add the Header row for CSV file.
csv += column.ColumnName + ',';
}
//Add new line.
csv += "\r\n";
foreach (DataRow row in dt.Rows)
{
foreach (DataColumn column in dt.Columns)
{
//Add the Data rows.
csv += row[column.ColumnName].ToString().Replace(",", ";") + ',';
}
//Add new line.
csv += "\r\n";
}
//Download the CSV file.
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=SqlExport.csv");
Response.Charset = "";
Response.ContentType = "application/text";
Response.Output.Write(csv);
Response.Flush();
Response.End();
}
}
}
}
}
}
Handling Commas
For handling commas inside of values when using string.Format(...), the following has worked for me:
var newLine = string.Format("\"{0}\",\"{1}\",\"{2}\"",
first,
second,
third
);
csv.AppendLine(newLine);
So to combine it with Johan's answer, it'd look like this:
//before your loop
var csv = new StringBuilder();
//in your loop
var first = reader[0].ToString();
var second = image.ToString();
//Suggestion made by KyleMit
var newLine = string.Format("\"{0}\",\"{1}\"", first, second);
csv.AppendLine(newLine);
//after your loop
File.WriteAllText(filePath, csv.ToString());
Returning CSV File
If you simply wanted to return the file instead of writing it to a location, this is an example of how I accomplished it:
From a Stored Procedure
public FileContentResults DownloadCSV()
{
// I have a stored procedure that queries the information I need
SqlConnection thisConnection = new SqlConnection("Data Source=sv12sql;User ID=UI_Readonly;Password=SuperSecure;Initial Catalog=DB_Name;Integrated Security=false");
SqlCommand queryCommand = new SqlCommand("spc_GetInfoINeed", thisConnection);
queryCommand.CommandType = CommandType.StoredProcedure;
StringBuilder sbRtn = new StringBuilder();
// If you want headers for your file
var header = string.Format("\"{0}\",\"{1}\",\"{2}\"",
"Name",
"Address",
"Phone Number"
);
sbRtn.AppendLine(header);
// Open Database Connection
thisConnection.Open();
using (SqlDataReader rdr = queryCommand.ExecuteReader())
{
while (rdr.Read())
{
// rdr["COLUMN NAME"].ToString();
var queryResults = string.Format("\"{0}\",\"{1}\",\"{2}\"",
rdr["Name"].ToString(),
rdr["Address"}.ToString(),
rdr["Phone Number"].ToString()
);
sbRtn.AppendLine(queryResults);
}
}
thisConnection.Close();
return File(new System.Text.UTF8Encoding().GetBytes(sbRtn.ToString()), "text/csv", "FileName.csv");
}
From a List
/* To help illustrate */
public static List<Person> list = new List<Person>();
/* To help illustrate */
public class Person
{
public string name;
public string address;
public string phoneNumber;
}
/* The important part */
public FileContentResults DownloadCSV()
{
StringBuilder sbRtn = new StringBuilder();
// If you want headers for your file
var header = string.Format("\"{0}\",\"{1}\",\"{2}\"",
"Name",
"Address",
"Phone Number"
);
sbRtn.AppendLine(header);
foreach (var item in list)
{
var listResults = string.Format("\"{0}\",\"{1}\",\"{2}\"",
item.name,
item.address,
item.phoneNumber
);
sbRtn.AppendLine(listResults);
}
}
return File(new System.Text.UTF8Encoding().GetBytes(sbRtn.ToString()), "text/csv", "FileName.csv");
}
Hopefully this is helpful.
This is a simple tutorial on creating csv files using C# that you will be able to edit and expand on to fit your own needs.
First you’ll need to create a new Visual Studio C# console application, there are steps to follow to do this.
The example code will create a csv file called MyTest.csv in the location you specify. The contents of the file should be 3 named columns with text in the first 3 rows.
https://tidbytez.com/2018/02/06/how-to-create-a-csv-file-with-c/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace CreateCsv
{
class Program
{
static void Main()
{
// Set the path and filename variable "path", filename being MyTest.csv in this example.
// Change SomeGuy for your username.
string path = #"C:\Users\SomeGuy\Desktop\MyTest.csv";
// Set the variable "delimiter" to ", ".
string delimiter = ", ";
// This text is added only once to the file.
if (!File.Exists(path))
{
// Create a file to write to.
string createText = "Column 1 Name" + delimiter + "Column 2 Name" + delimiter + "Column 3 Name" + delimiter + Environment.NewLine;
File.WriteAllText(path, createText);
}
// This text is always added, making the file longer over time
// if it is not deleted.
string appendText = "This is text for Column 1" + delimiter + "This is text for Column 2" + delimiter + "This is text for Column 3" + delimiter + Environment.NewLine;
File.AppendAllText(path, appendText);
// Open the file to read from.
string readText = File.ReadAllText(path);
Console.WriteLine(readText);
}
}
}
public static class Extensions
{
public static void WriteCSVLine(this StreamWriter writer, IEnumerable<string> fields)
{
const string q = #"""";
writer.WriteLine(string.Join(",",
fields.Select(
v => (v.Contains(',') || v.Contains('"') || v.Contains('\n') || v.Contains('\r')) ? $"{q}{v.Replace(q, q + q)}{q}" : v
)));
}
public static void WriteCSVLine(this StreamWriter writer, params string[] fields) => WriteCSVLine(writer, (IEnumerable<string>)fields);
}
This should allow you to write a csv file quite simply. Usage:
StreamWriter writer = new ("myfile.csv");
writer.WriteCSVLine("A", "B"); // A,B
Here is another open source library to create CSV file easily, Cinchoo ETL
List<dynamic> objs = new List<dynamic>();
dynamic rec1 = new ExpandoObject();
rec1.Id = 10;
rec1.Name = #"Mark";
rec1.JoinedDate = new DateTime(2001, 2, 2);
rec1.IsActive = true;
rec1.Salary = new ChoCurrency(100000);
objs.Add(rec1);
dynamic rec2 = new ExpandoObject();
rec2.Id = 200;
rec2.Name = "Tom";
rec2.JoinedDate = new DateTime(1990, 10, 23);
rec2.IsActive = false;
rec2.Salary = new ChoCurrency(150000);
objs.Add(rec2);
using (var parser = new ChoCSVWriter("emp.csv").WithFirstLineHeader())
{
parser.Write(objs);
}
For more information, please read the CodeProject article on usage.
One simple way to get rid of the overwriting issue is to use File.AppendText to append line at the end of the file as
void Main()
{
using (System.IO.StreamWriter sw = System.IO.File.AppendText("file.txt"))
{
string first = reader[0].ToString();
string second=image.ToString();
string csv = string.Format("{0},{1}\n", first, second);
sw.WriteLine(csv);
}
}
enter code here
string string_value= string.Empty;
for (int i = 0; i < ur_grid.Rows.Count; i++)
{
for (int j = 0; j < ur_grid.Rows[i].Cells.Count; j++)
{
if (!string.IsNullOrEmpty(ur_grid.Rows[i].Cells[j].Text.ToString()))
{
if (j > 0)
string_value= string_value+ "," + ur_grid.Rows[i].Cells[j].Text.ToString();
else
{
if (string.IsNullOrEmpty(string_value))
string_value= ur_grid.Rows[i].Cells[j].Text.ToString();
else
string_value= string_value+ Environment.NewLine + ur_grid.Rows[i].Cells[j].Text.ToString();
}
}
}
}
string where_to_save_file = #"d:\location\Files\sample.csv";
File.WriteAllText(where_to_save_file, string_value);
string server_path = "/site/Files/sample.csv";
Response.ContentType = ContentType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(server_path));
Response.WriteFile(server_path);
Response.End();
You might just have to add a line feed "\n\r".
I am trying to find a way to compare some text in 2 files and if a match is found .
Here are examples of the files;
'File A'
ex1,TEXAS,24
ex2,MIAMI,78
ex3,ATLANTA,56
ex4,NY,90
...
'File B'
ex1,JHON,1110
exA,DAVID,1060
exB,CATHY,230
ex4,ROBERT,1200
...
Using my 2 example files, I want to search them both and find matches(
ex1,TEXAS,24
&
ex4,NY,90
)??!
Here is my try
private void button4_Click(object sender, EventArgs e)
{
string fileA, fileB, fileC;
fileA = textBox1.Text;
fileB = textBox2.Text;
fileC = "result.txt";
string alphaFilePath = fileA;
List<string> alphaFileContent = new List<string>();
using (FileStream fs = new FileStream(alphaFilePath, FileMode.Open))
using (StreamReader rdr = new StreamReader(fs))
{
while (!rdr.EndOfStream)
{
}
}
string betaFilePath = fileB;
StringBuilder sb = new StringBuilder();
using (FileStream fs = new FileStream(betaFilePath, FileMode.Open))
using (StreamReader rdr = new StreamReader(fs))
{
while (!rdr.EndOfStream)
{
string[] betaFileLine = rdr.ReadLine().Split(Convert.ToChar(","));
}
}
using (FileStream fs = new FileStream(fileC, FileMode.Create)){
using (StreamWriter writer = new StreamWriter(fs))
{
writer.Write(sb.ToString());
}
} foreach (var item in alphaFileContent)
{
if (item.StartsWith(betaFileLine[0]))
{
sb.AppendLine(String.Format("{0}", betaFileLine[0]));
}
}
}
You can get all the lines of a file into an array using File.ReadAllLines:
var alphaFileContents = File.ReadAllLines(fileA);
In your code, you are checking to see which items from file A StartWith the same text as an item from file B up to the first comma. We can get all the prefixes (line contents up to the first comma) from fileB by using string.Split(',')[0], which splits the string into an array on the comma character, and then returns the first item (at index 0):
var betaFilePrefixes = File.ReadAllLines(fileB).Select(line => line.Split(',')[0]);
Now, we can find the similar items by getting all items in fileA that start with an item from fileB. The Where clause below says, "where any alpha item starts with an item in betaFilePrefixes:
var similarItems = alphaFileContents
.Where(alpha => betaFilePrefixes.Any(beta => alpha.StartsWith(beta)));
Then, you can write all the matching lines to the results file using File.WriteAllLines:
File.WriteAllLines(fileC, similarItems);
So, to put it all together, you can do this:
private void button4_Click(object sender, EventArgs e)
{
var fileA = textBox1.Text;
var fileB = textBox2.Text;
var fileC = "result.txt";
// Read the alpha file contents into a list
var alphaFileContents = File.ReadAllLines(fileA);
// Read each line of the beta file, and select the first part
// (up to the first comma) into a list
var betaFilePrefixes = File.ReadAllLines(fileB).Select(line => line.Split(',')[0]);
// Get all alpha lines that start with an item in the beta list
var similarItems = alphaFileContents
.Where(alpha => betaFilePrefixes.Any(alpha.StartsWith));
// Write the lines to our result file
File.WriteAllLines(fileC, similarItems);
}
var matches = File.ReadAllText(fileA).Split(',')
.Intersect(File.ReadAllText(fileB).Split(','));
I have a problem that I know people already asked here but I tried the solution they bring but it's not helping.
My problem: I'm doing a program in C# with 2 forms. My main form is used to read a file .txt and put the information in a DataGridView:
public void LireFichier()
{
DataGridView dataGridView1 = new DataGridView();
string delimeter = ";";
string tableName = "Clients";
string filePath = #"C:...\Clients.txt";
DataSet dataset = new DataSet();
using (StreamReader sr = new StreamReader(filePath))
{
dataset.Tables.Add(tableName);
dataset.Tables[tableName].Columns.Add("ID");
dataset.Tables[tableName].Columns.Add("Name");
dataset.Tables[tableName].Columns.Add("LastName");
dataset.Tables[tableName].Columns.Add("Datet");
dataset.Tables[tableName].Columns.Add("Price");
dataset.Tables[tableName].Columns.Add("Phone");
dataset.Tables[tableName].Columns.Add("ID box");
string allData = sr.ReadToEnd();
string[] rows = allData.Split("\r".ToCharArray());
foreach (string r in rows)
{
string[] items = r.Split(delimeter.ToCharArray());
dataset.Tables[tableName].Rows.Add(items);
}
this.dataGridView1.DataSource = dataset.Tables[0].DefaultView;
}
My second form is used to add a client in my .txt file :
private void btn_Confirmer_Click(object sender, EventArgs e)
{
string filePath = #"...\Clients.txt";
Client client = new Client();
client.Id = idClient++;
client.Name = tb_name.Text;
client.LastName = tb_lastName.Text;
client.Date = dtp_date.Value.ToString("dd-MMM-yyyy");
client.Price = Convert.ToInt32(tb_price.Text);
client.Phone = tb_telephone.Text;
client.ID_Box = Convert.ToInt32(tb_idbox.Text);
string clientInfo = client.Id.ToString() + ";" + client.Name.ToString() + ";" + client.LastName.ToString() + ";" + client.Date.ToString() + ";" +
client.Montant.ToString() + ";" + client.Phone.ToString() + ";" + client.ID_Boc.ToString() + ";";
using (StreamReader sr = new StreamReader(filePath))
{
string allData = sr.ReadToEnd() + clientInfo;
File.WriteAllText(filePath, allData);
}
this.Close();
}
The problem remains in the StreamReader or the File.WriteAllText no matter what I do I always encounter the same exception(System.IO.IOException) that my file is in use when I arrived to write(add a client) in the file in my second form.
The solution that I tried are:
put the using blocks
sr.Close()
sr.Dispose() even if I know that the using block call dispose at the end.
sr.Close() and sr.Dispose() at the end of the instruction.
Try changing to the following since I think the write is interfering with the read you are already performing.
string allData;
using (StreamReader sr = new StreamReader(filePath))
{
allData = sr.ReadToEnd() + clientInfo;
}
this.Close();
File.WriteAllText(filePath, allData);
Trelly indicated the most possible cause of you problem (file already in use). However, the solution containing exception handling should look like this:
try
{
string allData = null;
using (var sr = new StreamReader(filePath))
{
allData = sr.ReadToEnd() + clientInfo;
}
File.WriteAllText(filePath, allData);
}
catch (IOException exc)
{
// exception handling code
}
this.Close();
OR
It looks like you want to just append some text at the end of the file. File.AppendText is your friend:
using (StreamWriter sw = File.AppendText(filePath))
{
sw.Write(clientInfo);
}
To make your blocks of code thread safe, I would use a lock statement.
First declare object, you will perform lock on:
public static readonly Object Locker = new Object();
Then surround your parts of code, where you are working with file with lock statement:
lock(Locker)
{
//perform file operations
}
Remember that both forms have to refer to the same Locker object
After ReadToEnd, close the StreamReader before WriteAllText:
using (StreamReader sr = new StreamReader(filePath))
{
string allData = sr.ReadToEnd() + clientInfo;
sr.Close() ; // <---- add this instruction
File.WriteAllText(filePath, allData);
}
I have a csv file like this :
george,
nick,
mary,
john,
micheal
The user can make a file he likes. So he could have 4 or 5 or 28 lines for example.
I have an other csv file, that I assigned it to a ArrayList named fileList1 . This file is an agenda.
If a name in the agenda isn't in the csv, that will be given, then print a message.(this is what I need to find). The point is that both the csv can be dymanical. The number of lines is not standar.
I have also a table, colB[]. This table has the list of files that will compare with columns.
The problem is that I can not select a specific column in the arraylist because it is an arraylist.
ArrayList fileList1 = new ArrayList();
string stringforData;
private void button1_Click(object sender, EventArgs e)
{
// opens **BROWSE**
string filename = "";
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
filename = openFileDialog1.FileName;
textBox1.Text = filename;
// Read the file and display it line by line.
string line;
System.IO.StreamReader file1 = new System.IO.StreamReader(textBox1.Text); //reads the path from textbox
stringforData = file1.ReadLine();
while ((line = file1.ReadLine()) != null)
{
// bazei stoixeia mesa ston pinaka
fileList1.Add(line.Split(';'));//split the file and assign it in //the fileList1
}
file1.Close();
}
}
private void button3_Click(object sender, EventArgs e)
{
this.textBox2.Clear();
string[] colB = new string[];
for (int j = 0; j < colB.Length; j++)
{
if (Path.GetExtension(colB[j]) == ".csv")
{
string path = Path.GetDirectoryName(textBox1.Text);
string g = Path.Combine(path, colB[j]);
textBox2.Text += "the path is " + g + " " + Environment.NewLine;
System.IO.StreamReader gi = new System.IO.StreamReader(g);
string itemss;
ArrayList ArrayForLists=new ArrayList();
while ((itemss = gi.ReadLine()) != null)
{
ArrayForLists.AddRange(itemss.Split(';'));// assign to the arraylist the list that we are searching
}
}
It seems that an ArrayList is not a good option because you can't select the desired column. Why not use a free C# CSV parser:
http://www.filehelpers.com/
Found from here:
CSV parser/reader for C#?
In the link above there's also an example that loads a CSV into a DataTable, which gives you the option to reference a column (as opposed to an ArrayList).
Edit:
I've pasted the code from the given link:
static DataTable CsvToDataTable(string strFileName)
{
DataTable dataTable = new DataTable("DataTable Name");
using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0; Data Source = " + Directory.GetCurrentDirectory() + "; Extended Properties = \"Text;HDR=YES;FMT=Delimited\""))
{
conn.Open();
string strQuery = "SELECT * FROM [" + strFileName + "]";
OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter(strQuery, conn);
adapter.Fill(dataTable);
}
return dataTable;
}