C# - How to convert text file to formatted datatable in c#

Hi,

I want to convert text file in to datatable which is required particular highlighted value.

sample text file image

The above text file, i just want to convert into datatable.

i want to fetch only highlighted square values and remove duplicates then stored in to datatable.

Note : I need pnly highlighted portion data and want to remove remaining all..

Ho to get those data as datatable..?
Gani tptTech Lead cum developerAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Ryan ChongBusiness Systems Analyst , ex-Senior Application EngineerCommented:
can you upload a test1.txt here?
Gani tptTech Lead cum developerAuthor Commented:
pls. find attached for sample text file...
test1.txt
Pawan KumarDatabase ExpertCommented:
Please use this ..

Install TextFX plugin. < Notepad++ remove duplicates, remove blank lines and sort data in one operation > 

https://www.cathrinewilhelmsen.net/2012/05/16/notepad-remove-duplicates-remove-blank-lines-and-sort-data-in-one-operation/
Learn Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

Gani tptTech Lead cum developerAuthor Commented:
is it possible, without tool installation can we do it in code..?
Ryan ChongBusiness Systems Analyst , ex-Senior Application EngineerCommented:
try define a function like this:

private Boolean isValid(String[] s)
        {
            //Put your validation logic here
            if (s.Length == 2)
            {
                return (s[1].Trim().Length == 10);
            }
            else
            {
                return false;
            }
        }

Open in new window


and then put codes like this:

DataTable tmp = new DataTable("myTable");
            DataColumn col = tmp.Columns.Add("ID", typeof(String));
            col.AllowDBNull = false;
            col.Unique = false;

            foreach (String line in File.ReadLines(@"D:\test1.txt"))
            {
                string[] s = line.Split(new string[] { "==>" }, StringSplitOptions.None);
                if (isValid(s))
                {
                    DataRow row = tmp.NewRow();
                    row[col] = s[1].Trim();
                    tmp.Rows.Add(row);
                }
            }
            DataTable tbl = tmp.AsEnumerable()
                            .GroupBy(x => x.Field<String>("ID"))
                            .Select(y => y.First())
                            .CopyToDataTable();

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Gani tptTech Lead cum developerAuthor Commented:
getting error.

Error : The source contains no DataRows.

pls. find error scrren shot.

Error.png

PS : my data value is not a static. like "A_E001-A-H-BCA-S" sometimes it is more than 10 characters also sometimes less than 10 characters also.
if the above condition is fine, then my problem is solved...

example below..

20/5/2016 11:17:44 AM ==> A_E001-A-H
20/5/2016 11:17:44 AM ==> A_E002-A-H-MMA-IF
20/5/2016 11:17:44 AM ==> A_E003-A-H
20/5/2016 11:17:44 AM ==> A_E004-A-H-VD
20/5/2016 11:17:45 AM ==> A_E001-A-H-S
20/5/2016 11:17:45 AM ==> A_E006-A-H-KK-06
20/5/2016 11:17:45 AM ==> A_E007-A-H
20/5/2016 11:17:45 AM ==> A_E008-A-H
20/5/2016 11:17:45 AM ==> A_E001-A-H

if the above condition is fine, then my problem is solved...
Ryan ChongBusiness Systems Analyst , ex-Senior Application EngineerCommented:
my data value is not a static. like "A_E001-A-H-BCA-S" sometimes it is more than 10 characters also sometimes less than 10 characters also.
so you got to build that logic in function below:

private Boolean isValid(String[] s)
Pawan KumarDatabase ExpertCommented:
Tools generally works best in these scenario. Also note that they are free and can really increase the development speed.
Gani tptTech Lead cum developerAuthor Commented:
can you give some more idea to apply the mentioned logic for the below code.....?

private Boolean isValid(String[] s)
        {
            //Put your validation logic here
            if (s.Length == 2)
            {
                return (s[1].Trim().Length == 10);
            }
            else
            {
                return false;
            }
        }
Snarf0001Commented:
Do you want only the "A_E001-A-H" codes, or are you looking to include the dates as well?
And you want to trim out  the rows above it, correct?

In which case is there any further logic to the pattern?  We still need to tell the difference between "A_E001-A-H" for example, and "1 :C:\projects\test".  If the code always starts with "A_" for example, that would work.


Tools generally works best in these scenario.
There's a lot of other formatting and filtering that has to be done, (such as limiting the rows as per above), and it's already being done in code, hence the request to put it into a datatable.  Running through a plugin would be a pointless waste of resources for what will end up being an easy, quick, customizable loop.
Ryan ChongBusiness Systems Analyst , ex-Senior Application EngineerCommented:
a regular expression verification could be good enough, but you got to tell us your ID formats
Gani tptTech Lead cum developerAuthor Commented:
Thanks.

The logic is correct and perfect.

But, i am getting error while reading a text file.

the text file stored in temp folder.


anything need to modify the code below..

var contents = File
                .ReadAllLines(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, txtfilePath));

Error : The process cannot access the file 'C:\Users\P0010\AppData\Local\Temp\Report_Log.txt' because it is being used by another process.

Pls. find attached error.
Error.png
Pawan KumarDatabase ExpertCommented:
Is that file opened somewhere...?
Gani tptTech Lead cum developerAuthor Commented:
no. log file is placed in local temp folder and i checked there is no open at all.
Ryan ChongBusiness Systems Analyst , ex-Senior Application EngineerCommented:
log file is placed in local temp folder and i checked there is no open at all.
the file is probably locked by your own program? try make sure it's not.
Gani tptTech Lead cum developerAuthor Commented:
" try make sure it's not"

How to check whether it is locked or not...
Ryan ChongBusiness Systems Analyst , ex-Senior Application EngineerCommented:
How to check whether it is locked or not...

try download Process Explorer:

https://docs.microsoft.com/en-us/sysinternals/downloads/process-explorer

and then go to menu Find > Find Handle or DLL...

A search dialogue is opened, try type in the file name and do a Search there.
Gani tptTech Lead cum developerAuthor Commented:
Thanks for your suggestions..

I found the exact problem as mentioned below.

when i use  var contents = File.ReadLines(@"C:\Temp\Report_Log.txt;    ==> It's working fine (Path I).

when i use  var contents = File.ReadLines(@"C:\Users\P0010\AppData\Local\Temp\Report_Log.txt");  ==> getting error (Path II).

Both are referred temp folder only.

But, first path is working fine. second not

second (Path II) refer from  "C:\Users\P0010\AppData\Local\Temp\"  ==> is there any problem over there in the path...?????
Ryan ChongBusiness Systems Analyst , ex-Senior Application EngineerCommented:
But, first path is working fine. second not
so it means:

C:\Temp\Report_Log.txt;
is not locked by any process but:

C:\Users\P0010\AppData\Local\Temp\Report_Log.txt
is being locked by some process

you can:

1. try to use a different file name and see if that work?
2. use a different path and see if that work?
Gani tptTech Lead cum developerAuthor Commented:
Actually i tried as mentioned two steps (filename change and path change).

I thing, i am writing a text file in same folder and reading a text file same folder.

is there any issue writing and reading same folder or same file....?

why i am using appdata temp file, it will automatically delete file End of the day. we are generating many log files. for the reference purpose only we are using appdata temp folder.

But, C:\\temp ==> it is manually edit file.

that's why...?
Gani tptTech Lead cum developerAuthor Commented:
Thank you all.

i tried different solution for the same  code.

1. copied same file to another folder.

 2. read the file from copied folder.

3. after done all the process, delete the file in copied folder.


it's working.

Thanks Ryan Chong...kudoos...
Gani tptTech Lead cum developerAuthor Commented:
Good solution.. kudoos..
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.