Social Icons

Pages

Thursday, September 12, 2013

FTP and file handling in C#

In this article I am going to discuss some helpful code snippets in C# to accomplish FTP File operations. I hope this will make your coding easier.

To connect to the FTP server we can use the FtpWebRequest C# object under the System.Net namespace.

Check whether file exists
private bool FtpDirectoryExists(string Directory, string Username, string Password)
        {
            //Directory = "ftp://" + FTPpath + "/" + Selectedfile;
            FtpWebRequest fwr = (FtpWebRequest)WebRequest.Create(Directory);
            FtpWebResponse fRes = default(FtpWebResponse);
            fwr.Credentials = new NetworkCredential(Username, Password);
            fwr.Method = WebRequestMethods.Ftp.GetFileSize;
            try
            {
                fRes = (FtpWebResponse)fwr.GetResponse();
                //no error occured then the file is exists 
                return true;
            }
            catch (WebException ex)
            {
                fRes = (FtpWebResponse)ex.Response;
                //Error occured then the file doesn't exists 
                if (FtpStatusCode.ActionNotTakenFileUnavailable == fRes.StatusCode)
                {
                    return false;
                }
                else
                {
                    //Any other errors you need to handle here 
                    return false;
                }
            }
        }
 Listing all file Names
public DataTable GetFTPFile(string Directory, string Username, string Password)
        {
            DataTable dtFtpFileDetails = new DataTable();
            dtFtpFileDetails.Columns.Add("FileName", typeof(string));

            try
            {
                //Get Directory Details
                FtpWebRequest ftpClientdir;
                ftpClientdir = (FtpWebRequest)FtpWebRequest.Create(Directory);
                ftpClientdir.Credentials = new NetworkCredential(Username, Password);
                ftpClientdir.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                WebResponse response = ftpClientdir.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());

                //File names
                FtpWebRequest ftpClient;
                ftpClient = (FtpWebRequest)FtpWebRequest.Create(Directory);
                ftpClient.Credentials = new NetworkCredential(Username, Password);
                ftpClient.Method = WebRequestMethods.Ftp.ListDirectory;
                WebResponse response2 = ftpClient.GetResponse();
                StreamReader reader2 = new StreamReader(response2.GetResponseStream());

                //read file/directory names into arraylist
                string lsdirectory = reader2.ReadLine();
                ArrayList lsnames = new ArrayList();
                while (lsdirectory != null)
                {
                    lsnames.Add(lsdirectory);
                    lsdirectory = reader2.ReadLine();
                }

                //read through directory details response
                string line = reader.ReadLine();
                while (line != null)
                {
                    if (!line.StartsWith("d") && !line.EndsWith(".")) //"d" = dir don't need "." or ".." dirs
                    {
                        foreach (String chk in lsnames) //compare basic dir output to detail dir output to get dir name
                        {
                            if (line.EndsWith(chk))
                            {
                                DataRow dr = dtFtpFileDetails.NewRow();
                                dr["FileName"] = chk;
                                dtFtpFileDetails.Rows.Add(dr);
                            }
                        }
                    }
                    line = reader.ReadLine();
                }
                return dtFtpFileDetails;
            }
            catch (Exception)
            {
                return dtFtpFileDetails;
            }
        }
Download Files

public bool downloadfile(string Directory, string Username, string Password, string Localpath, string filename)
        {
            try
            {
                string localPath = Localpath + "\\";
                FtpWebRequest requestFileDownload = (FtpWebRequest)WebRequest.Create(Directory + "/" + filename);
                requestFileDownload.Credentials = new NetworkCredential(Username, Password);
                requestFileDownload.Method = WebRequestMethods.Ftp.DownloadFile;

                FtpWebResponse responseFileDownload = (FtpWebResponse)requestFileDownload.GetResponse();

                Stream responseStream = responseFileDownload.GetResponseStream();
                FileStream writeStream = new FileStream(localPath + filename, FileMode.Create);

                int Length = 2048;
                Byte[] buffer = new Byte[Length];
                int bytesRead = responseStream.Read(buffer, 0, Length);

                while (bytesRead > 0)
                {
                    writeStream.Write(buffer, 0, bytesRead);
                    bytesRead = responseStream.Read(buffer, 0, Length);
                }

                responseStream.Close();
                writeStream.Close();

                requestFileDownload = null;
                responseFileDownload = null;
                return true;
            }
            catch (Exception ex)
            {
             
                return false;
            }
        }
Upload File
        private bool UploadfiletoFTP(string LocalfilePath, string FileName, string Directory, string Username, string Password)
        {

            try
            {
                FtpWebRequest ftpClient = (FtpWebRequest)FtpWebRequest.Create(Directory + "/" + FileName);
                ftpClient.Credentials = new System.Net.NetworkCredential(Username, Password);
                ftpClient.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
                ftpClient.UseBinary = true;
                ftpClient.KeepAlive = true;
                System.IO.FileInfo fi = new System.IO.FileInfo(LocalfilePath + "/" + FileName);
                ftpClient.ContentLength = fi.Length;
                byte[] buffer = new byte[4097];
                int bytes = 0;
                int total_bytes = (int)fi.Length;
                System.IO.FileStream fs = fi.OpenRead();
                System.IO.Stream rs = ftpClient.GetRequestStream();
                while (total_bytes > 0)
                {
                    bytes = fs.Read(buffer, 0, buffer.Length);
                    rs.Write(buffer, 0, bytes);
                    total_bytes = total_bytes - bytes;
                }
                //fs.Flush();
                fs.Close();
                rs.Close();
                FtpWebResponse uploadResponse = (FtpWebResponse)ftpClient.GetResponse();
                string value = uploadResponse.StatusDescription;
                uploadResponse.Close();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
Delete File
        private bool DeleteFtpFile(string Directory, string Username, string Password, string Filename)
        {

            try
            {
                FtpWebRequest requestFileDelete = (FtpWebRequest)WebRequest.Create(Directory + "/" + Filename);
                requestFileDelete.Credentials = new NetworkCredential(Username, Password);
                requestFileDelete.Method = WebRequestMethods.Ftp.DeleteFile;
                FtpWebResponse responseFileDelete = (FtpWebResponse)requestFileDelete.GetResponse();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

References:
http://www.techrepublic.com/blog/how-do-i/how-do-i-use-c-to-upload-and-download-files-from-an-ftp-server/ 
http://khanrahim.wordpress.com/2010/09/03/file-download-upload-delete-in-ftp-location-using-c/

Friday, September 6, 2013

Improving Stored Procedure performance

This article provides some best practices to improve SP performance, which will improve overall application performance.

There are many more other best practices, which I will discuss in future.


1. Using SET NOCOUNT ON statement
Use SET NOCOUNT ON at the beginning of your stored procedures.When SET NOCOUNT is ON,    the count of effected rows is not returned. This improves the performance of stored procedures by reducing network traffic.

2. Do not use the ‘sp_’ in the stored procedure name 
Do not start the stored procedures name with “sp” because sp_ prefix makes SQL Server look at the master database for a compiled plan. It needs an exclusive compile.

3. Use schema name with object name

This helps finding the data directly instead of searching the other possible schema. 
Select * From dbo.tbl_Customer-- Preferred method
Select * From tbl_Customer -- Avoid this method 
4. Use TRY-Catch for error handling

5. Use IF EXISTS (SELECT 1) instead of (SELECT *)

To minimize the data for processing and network transferring use 1 in the SELECT clause of an internal statement.

IF EXISTS (Select CustomerID From dbo.Tbl_Customer
Where CustomerID = 1 )
6. Do not use those columns in the select statement which are not required. Don’t use select * statement

7. Try to avoid using cursors whenever possible

Cursor uses a lot of resources for overhead processing to maintain current record position in a record set and this decreases the performance.


References:
http://blog.sqlauthority.com/2010/02/16/sql-server-stored-procedure-optimization-tips-best-practices/

http://www.c-sharpcorner.com/blogs/2117/improving-stored-procedure-performance-checklist.aspx