How recursively delete a directory files in C#,that has Permission problem

by daz 10/29/2009 6:48:00 PM

It is sometime difficulte to delete folder or directory in your machine with applications. 

This is one of the easiest way. to resset the files permissions before deleting them.

public static bool DeleteFolder(string  dir)

{

   bool result = false;

   string[] files = Directory.GetFiles(dir);

   string[] directory = Directory.GetDirectories(dir);

foreach (string file in files)

     File.SetAttributes(file, FileAttributes.Normal);

     File.Delete(file);

foreach (string st in  directory)

{

  DeleteDirectory(st);

    Directory.Delete(dir, false ); 

    return result;

} }}

 

Tags:

Upload CSV in SQL Database using Linq

by daz 10/20/2009 4:46:00 AM

 In my previous article http://davidz.afriklink.com/post/Creating-and-Deploying-a-dtsx-package-to-upload-CSVxcl-in-Database.aspx 

I encounter a problem where the system generating csv file create some files with empty cell.As you know it is hard inserting empty data to an integer field in a database. I did not want to change my emailId that is Integer in the table to be a varchar for example.

So my solution was to create another function that will get all the files that was rejected by the dtsx package and read them line by line

private void ErrorCorrection(Settings setting) //setting has all my configuration meaning directories for all files

 {

 string[] files = Directory.GetFiles(setting.ErrorFolder, @"*.csv", SearchOption.TopDirectoryOnly); //Loop through all  csv files error s ones   

for (int i = 0; i < files.Length; i++) foreach (string errorFile in _logFilesError) // Log exist

 {

_logFilesError.Add(files[i]);

} 

{

if (!File.Exists(errorFile)) continue 

var fileInfo = new FileInfo(errorFile);

string conn = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileInfo.DirectoryName + ";Extended Properties='Text;HDR=Yes;FMT=CSVDelimited'"; 

OleDbConnection cn = new OleDbConnection(conn);

OleDbCommand cmd = new OleDbCommand(@"SELECT * FROM [" + fileInfo.Name + "]"

, cn); OleDbDataAdapter da = new OleDbDataAdapter(cmd);  

 

DataTable dt = new DataTable();

 

cn.Open(); 

var properties = (from r in

dt.AsEnumerable()  

where r[3].ToString() != string.Empty && r[4].ToString() != string.Empty select r);

foreach (var data in properties) //

{

 TESTCSVdAO dao = new TESTCSVdAO();  

int.Parse(data[2].ToString()), int.Parse(data[3].ToString()),

int.Parse(data[4].ToString()));  

////move to archive folder csv folder

 FileInfo fi = new FileInfo(errorFile.ToString());

string destination = setting.Archive;

}

}

 ###########Linq Action ##########  we can accomplish the sAME with LINQ to CSV

string[] csvlines = File.ReadAllLines(@errorFile); 

var query = from csvline in csvlines let data = csvline.Split(',')

 select new

 

{

type = data[0],dsnStatus = data[1],batchid = data[2],EmailId = data[3],

pBatchid = data[3]};

var result = from q in

query where q.batchid != null || q.pBatchid != null select q;  

foreach (var r in result)  

TESTCSVdAO dao = new TESTCSVdAO();  

int.Parse(r.batchid), int.Parse(r.EmailId), int.Parse(r.pBatchid)); 

 

dao.GetSumaryCampaign(r.type, r.dsnStatus,

 

{

}

 

 

 

dao.GetSumaryCampaign(data[0].ToString(), data[1].ToString(),

 

 

 

da.Fill(dt);

Creating and Deploying a .dtsx package to upload CSV,xcl in Database

by daz 10/5/2009 11:24:00 PM

I had a project where a mail service will get mail status from MTA response, parse the data into a CSV files.

Each files may go up to 400 000 records. Those data need to be in my database to update a table.

To insert all of this row by row and wait for the next file is time consuming. Thus, i create a windows service and an SQL DTSX packages to perform this task. pretty fast and pretty nice.

1. Create the DTSX package in SQL manager studio

2. Create your win services

Here is the code .

 public partial class DZ_DTSService : ServiceBase new ArrayList();

{

Timer _timer;

ArrayList _logFiles =

public DZ_DTSService()

{new Timer(new TimerCallback(OnNextMinute), null , Timeout.Infinite, Timeout.Infinite);

_timer =

InitializeComponent();

}

public void OnNextMinute(object state)

// Read config  

Settings dzSetting;

if (!ReadSettings(out 

dzSetting))  

 return;  

FillStack(dzSetting);

}

void FillStack(Settings settings)

{

try  

{

string[] files = Directory.GetFiles(settings.CsvFolder, @"*.csv"

, SearchOption.TopDirectoryOnly); 

for (int

i = 0; i < files.Length; i++)

{_logFiles.Add(files[i]);

}

RunSSISPackageService(settings);

}

catch (Exception

ex)

{

WriteError(ex);

}

}

protected override void OnStart(string

[] args)

{ Settings dzSetting;

if (!ReadSettings(out

dzSetting))

 

return ;

AppLogger.WriteInformation(

 

"Service has Started "

);

_timer.Change(0, dzSetting.Sleep);

 

//sec + 000 Milisecond every 5 minute run service = 5*60 000

 }

 

protected override void

 

OnStop()

{

AppLogger.WriteInformation(

 

"Service has Stopped "

);

}

//read setting for the application

//this will return all necessary variable stored in the config file for later use

 

bool ReadSettings(out

Settings settings)

{

 

bool success = true;

Settings setting = AppSettings.ReadSettings();

settings = (success)?(setting):(

 

null

); 

 

return

success;

}

 

protected void

RunSSISPackageService(Settings setting)

{

Application app =

 

new

Application();

Package package = 

null ;

string pkgLocation = setting.CsvPackage;  

try

 

{

package = app.LoadPackage(pkgLocation,

 

null);

//load the package file

package.Connections[ 

"DestinationConnectionOLEDB"].ConnectionString = setting.Connection;

//The Database connection string get from app config

foreach (string logFile in

_logFiles)

// Log exist 

if

(!File.Exists(logFile)) 

continue

try

{

// string fileName = logFile.ToString();  

package.Connections[

"SourceConnectionFlatFile"].ConnectionString = logFile;

//change connection string 

//for each files since you may have multiple file waiting  

//Execute DTSX.

DTSExecResult results = package.Execute();

 

// great way to write error from the application 

//log those errors in a log file

 if

(results == Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure)

{

 

foreach (Microsoft.SqlServer.Dts.Runtime.DtsError local_DtsError in

 package.Errors)

{

WriteError(setting,

"Error while Excecuting File: "

 

+ logFile +

" Code: "

+ local_DtsError.Description);

}

}

 

else

//delete if update DB //move file

{

 

//Move the file to an archive directory..

 

FileInfo fi =

new

FileInfo(logFile.ToString());

 

string

destination=setting.Archive;

fi.MoveTo(destination + fi.Name);

WriteSuccess(setting, fi.Name);

}

}

catch (Exception

ex)

{

WriteError(setting, ex.Message );

}

}

}

 

 

catch (Exception

ex)

{

WriteError(setting,ex.Message);

}

 

finally

 

{

 

 

if (package != null

)

{

package.Dispose();

package =

 

null;

 

}

}

}

 

Tags: , ,

About the author

Name of author
DavidZ
.Net Programmer
E-mail me Send mail

Calendar

<<  August 2010  >>
MoTuWeThFrSaSu
2627282930311
2345678
9101112131415
16171819202122
23242526272829
303112345

View posts in large calendar

Recent comments

Authors

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2010

Sign in