Forum guidelines
C# obtain data from file name
Posted By dc on 04 Jan 2013

My goal is to parse out a company name and contact name  that is the actual filename of the excel spreadsheet.

I will use this information in a sql server 2008 r2 database to obtain other related information for the company and contact person.
My problem is the file name is manually keyed in my the user who runs the sql server 2008 r2 reports (ssrs) on the standard edition.
Is there away you would suggest that I try to parse out the  company and contact name from the file name? There are delimiters between the company and contact names how the delimiters may change.
(Note: I am intending on using this method instead of opening up the excel spreadsheet to
obtain the information I am looking for. I think that there would be alot of code that is required to open the excel spreadsheet and get the data I am looking for in certain rows and columns. If obtaining the code from an excel spreadsheet is not so bad, can you show me the code on how to accomplish this goal?)

Can you show me in code and/or point me to a reference on how to accomplish my goal?

Re: C# obtain data from file name
Posted By Vulpes on 04 Jan 2013  
As long as the company and contact names are separated from each other and the rest of the file name by delimiters selected from a pre-defined set or which (at worst) cannot themselves be part of the company and contact names, then it should be possible to parse them out from the file name.

I would envisage using String.Split, Regex.Split or 'ad hoc' methods to achieve this depending on how complex the set of potential delimiters and/or the structure of the file name is.

This is likely to be much easier (and quicker) than obtaining these details from an Excel spreadsheet.

If you could give me some samples, I'll see if I can come up with some code.

  • 0
  • 0
Re: C# obtain data from file name
Posted By Vulpes on 05 Jan 2013   Accepted Answer
OK, assuming the underscore is used as a delimiter, then the following should parse out the customer and contact names regardless of whether the underscore is surrounded by spaces or not:

using System;
using System.IO;

class Test
   static void Main()
      string filePath = @"C:\app1\12_2012\customer name _ contact name.xls";
      string temp = Path.GetFileNameWithoutExtension(filePath);
      string[] names = temp.Split('_');
      string customerName = names[0].TrimEnd();
      string contactName = names[1].TrimStart(); 
      Console.WriteLine("Customer = '{0}'", customerName);
      Console.WriteLine("Contact  = '{0}'", contactName);

Download Free e-Books


Custom Software Development
MCN is your source for developing solutions involving websites, mobile apps, cloud-computing, databases, BI, back-end services and processes and client-server applications.