how to get the latest file in a FTP or directory Based On Date using C#.net

// Your FTP site
string ftpPath = "ftp://some/localtion/to/ftp/directory/";
 
// Some expression to match against the files...do they have a consistent name? This example would find XML files that had 'some_string' in the file name
Regex matchExpression = new Regex("^some_string.+\.xml$", RegexOptions.IgnoreCase);
 
// Only files greater than this value
DateTime cutOff = DateTime.Now.AddDays(-10);
 
List<ftplineresult> results = FTPHelper.GetFilesListSortedByDate(ftpPath, matchExpression, cutOff);
</ftplineresult>
 
 
 
 
 
 
namespace FTP.Utilities
{
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Net;
    using System.IO;
    using System.Text.RegularExpressions;
    public enum ListStyle
    {
        Unix,
        Windows
    }
    public class FTPLineResult
    {
        public ListStyle Style { get; set; }
        public string Name { get; set; }
        public DateTime DateTime { get; set; }
        public bool IsDirectory { get; set; }
        public long Size { get; set; }
    }
    /// <summary>
    /// from http://blogs.msdn.com/adarshk/archive/2004/09/15/230177.aspx
    /// </summary>
    public class FTPLineParser
    {
        private Regex winStyle = new Regex(@"^(?<month>\d{1,2})-(?<day>\d{1,2})-(?<year>\d{1,2})\s+(?<hour>\d{1,2}):(?<minutes>\d{1,2})(?<ampm>am|pm)\s+(?<dir>[<]dir[>])?\s+(?<size>\d+)?\s+(?<name>.*)$", RegexOptions.IgnoreCase);
        public FTPLineResult Parse(string line)
        {
            Match match = winStyle.Match(line);
            if (match.Success)
            {
                return ParseMatch(match.Groups, ListStyle.Windows);
            }
            throw new Exception("Invalid line format");
        }
        private FTPLineResult ParseMatch(GroupCollection matchGroups, ListStyle style)
        {
            string dirMatch = (style == ListStyle.Unix ? "d" : "<dir>");
            FTPLineResult result = new FTPLineResult();
            result.Style = style;
            result.IsDirectory = matchGroups["dir"].Value.Equals(dirMatch, StringComparison.InvariantCultureIgnoreCase);
            result.Name = matchGroups["name"].Value;
            result.DateTime = new DateTime(2000 + int.Parse(matchGroups["year"].Value), int.Parse(matchGroups["month"].Value), int.Parse(matchGroups["day"].Value), int.Parse(matchGroups["hour"].Value) + (matchGroups["ampm"].Value.Equals("PM") && matchGroups["hour"].Value != "12" ? 12 : 0), int.Parse(matchGroups["minutes"].Value), 0);
            if (!result.IsDirectory)
                result.Size = long.Parse(matchGroups["size"].Value);
            return result;
        }
    }
    /// <summary>
    /// FTP Class to retreieve files that match an expression and file date cutoff
    /// </summary>
    public class FTPHelper
    {
        /// <summary>
        /// Get a list of files from the FTP server, in a specified path, that match a naming regular expression, and who's file date is after a cutoff
        /// </summary>
        /// <param name="ftpPath">The path the to FTP location</param>
        /// <param name="nameRegex">Regurlar expression to match when finding files</param>
        /// <param name="cutoff">A datetime that files on the FP server must be greater than</param>
        /// <returns></returns>
        public static List<FTPLineResult> GetFilesListSortedByDate(string ftpPath, Regex nameRegex, DateTime cutoff)
        {
            List<FTPLineResult> output = new List<FTPLineResult>();
            FtpWebRequest request = FtpWebRequest.Create(ftpPath) as FtpWebRequest;
            ConfigureProxy(request);
            request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
            FtpWebResponse response = request.GetResponse() as FtpWebResponse;
            StreamReader directoryReader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.ASCII);
            var parser = new FTPLineParser();
            while (!directoryReader.EndOfStream)
            {
                var result = parser.Parse(directoryReader.ReadLine());
                if (!result.IsDirectory && result.DateTime > cutoff && nameRegex.IsMatch(result.Name))
                {
                    output.Add(result);
                }
            }
            // need to ensure the files are sorted in ascending date order
            output.Sort(
                new Comparison<FTPLineResult>(
                    delegate(FTPLineResult res1, FTPLineResult res2)
                    {
                        return res1.DateTime.CompareTo(res2.DateTime);
                    }
                )
            );
            return output;
        }
        /// <summary>
        /// set up the web proxy
        /// </summary>
        /// <param name="request"></param>
        private static void ConfigureProxy(FtpWebRequest request)
        {
            request.Proxy = WebRequest.GetSystemWebProxy();
            request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
        }
    }
} 

Compare two string arrays using C#.Net


please try this, use linq
string[] array1 = new string[] { "Data", "Account", "credit"
"Debit" };//This array Contain constant vlues
string[] array2 = new string[] { "Data1", "Account1", "credit"
"Debit" };//This array may be same or may be diff
string[] array3 = new string[] { "Data", "Account", "credit",
 "Debit" };//This array Contain constant vlues
//i have to comapre this two arrays ...if two string arrays values same 
//i have to add this below code..
var diff = from item in array1 where array2.Contains(item)
 select item;
if (diff.Count() == array1.Length )
{
 //the same
 MessageBox.Show("array1 vs array2 the same");
}
else
{
 //not the same
 MessageBox.Show("array1 vs array2 not the same");
}
var diff2 = from item in array1 where array3.Contains(item) select item;
if (diff2.Count() == array1.Length)
{
 //the same
 MessageBox.Show("array1 vs array3 the same");
}
else
{
 //not the same
 MessageBox.Show("array1 vs array3 not the same");
}


-------------------------------------------------------------------------------------------------------


int[] array1 = { 1,2,3,4,5 };
      int[] array2 = { 2,5,6,7,8 };

      Console.WriteLine("What array1 has that array2 doesn't:");
      foreach (int i in array1.Except(array2))
      {
        Console.WriteLine(i);
      }

      Console.WriteLine();

      Console.WriteLine("What array2 has that array1 doesn't:");
      foreach (int i in array2.Except(array1))
      {
        Console.WriteLine(i);
      }


-----------------------------------------------------------------------
var list1 = string[] {"1", "2", "3", "4", "5", "6"};
var list2 = string[] {"2", "3", "4"};
listDiff = list1.Except(list2); //This gets the desire result for different items
//This doesn't give me desire result. Comes out as {"1", "5", "6", "2", "3", "4"};


-------------------------------------------------------

foreach (string com in com2 )
{
    if (!com1.Contains(com))
    {
        MessageBox.Show(com);
    }
}


File Download, Upload, Delete in FTP Location using C#.Net

File Download, Upload, Delete in FTP Location using C#.Net

If you have difficulties with FTP File operations, you are at the right place. I am going to present some self explanatory code snippets in C# to accomplish FTP FILE operations like downloading, uploading and deleting.

using System.Net;
First of all, this directive is mandatory for FTP Operations.
File Download From FTP:

string localPath = @"G:\FTPTrialLocalPath\";
string fileName = "arahimkhan.txt";

FtpWebRequest requestFileDownload = (FtpWebRequest)WebRequest.
Create("ftp://localhost/Source/" + fileName);
requestFileDownload.Credentials = new NetworkCredential("khanrahim",
 "arkhan22");
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;
File Upload to FTP:

string localPath = @"G:\FTPTrialLocalPath\";
string fileName = "arahimkhan.txt";

FtpWebRequest requestFTPUploader = (FtpWebRequest)WebRequest.
Create("ftp://127.0.0.1/Destination/" + fileName);
requestFTPUploader.Credentials = new NetworkCredential("khanrahim", 
"arkhan22");
requestFTPUploader.Method = WebRequestMethods.Ftp.UploadFile;

FileInfo fileInfo = new FileInfo(localPath + fileName);
FileStream fileStream = fileInfo.OpenRead();

int bufferLength = 2048;
byte[] buffer = new byte[bufferLength];

Stream uploadStream = requestFTPUploader.GetRequestStream();
int contentLength = fileStream.Read(buffer, 0, bufferLength);

while (contentLength != 0)
{
 uploadStream.Write(buffer, 0, contentLength);
 contentLength = fileStream.Read(buffer, 0, bufferLength);
}
                    
uploadStream.Close();
fileStream.Close();

requestFTPUploader = null;
File Delete From FTP:

string fileName = "arahimkhan.txt";

FtpWebRequest requestFileDelete = (FtpWebRequest)WebRequest.
Create("ftp://localhost/Source/" + fileName);
requestFileDelete.Credentials = new NetworkCredential("khanrahim", 
"arkhan22");
requestFileDelete.Method = WebRequestMethods.Ftp.DeleteFile;

FtpWebResponse responseFileDelete = (FtpWebResponse)requestFileDelete.
GetResponse();
Retrieve File List from FTP Directory:

FtpWebRequest request = (FtpWebRequest)WebRequest.
Create("ftp://localhost/Source");
request.Credentials = new NetworkCredential("khanrahim", "arkhan22");
request.Method = WebRequestMethods.Ftp.ListDirectory;

StreamReader streamReader = new StreamReader(request.GetResponse().
GetResponseStream());

string fileName = streamReader.ReadLine();

while (fileName != null)
{
 Console.Writeline(fileName );
 fileName = streamReader.ReadLine();
}

request = null;
streamReader = null;


using System.IO;
You have to use this directive for Local File Operation.
Retrieve File List from Local Directory:

string localPath = @"G:\FTPTrialLocalPath\";

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

foreach (string filepath in files)
{
  string fileName = Path.GetFileName(filepath);
  Console.WriteLine(fileName);
}

Get Files Write and Modified Date using C#

Get File Time [C#]

This example shows how to get file time informations, when any file was created, last modified or accessed. To get file datetime info you can use either static methods of File class or instance methods of FileInfo class.

Get file times using File class

Use File class when you want to get just one specific time, for example if you are only interested in a file last modification time. To do this use static method File.GetLastWri­teTime with file path as a parameter. File class also provides static methods to get file creation time or file last access time. You can also get this times in UTC, e.g. to get file last write time in UTC use File.GetLastWri­teTimeUtc.
[C#]
// local times
DateTime creationTime = File.GetCreationTime(@"c:\file.txt");
DateTime lastWriteTime = File.GetLastWriteTime(@"c:\file.txt");
DateTime lastAccessTime = File.GetLastAccessTime(@"c:\file.txt");

// UTC times
DateTime creationTimeUtc = File.GetCreationTimeUtc(@"c:\file.txt");
DateTime lastWriteTimeUtc = File.GetLastWriteTimeUtc(@"c:\file.txt");
DateTime lastAccessTimeUtc = File.GetLastAccessTimeUtc(@"c:\file.txt");

// write file last modification time (local / UTC)
Console.WriteLine(lastWriteTime);     // 9/30/2007 2:16:04 PM
Console.WriteLine(lastWriteTimeUtc);  // 9/30/2007 6:16:04 PM

Get file times using FileInfo class

Use instance of FileInfo class when you want to get more than one file time or any other informations about the file (like file attributes). Advantage is that you will get all needed informations just in one disk access. See following example.
[C#]
FileInfo fileInfo = new FileInfo(@"c:\file.txt");

// local times
DateTime creationTime = fileInfo.CreationTime;
DateTime lastWriteTime = fileInfo.LastWriteTime;
DateTime lastAccessTime = fileInfo.LastAccessTime;

// UTC times
DateTime creationTimeUtc = fileInfo.CreationTimeUtc;
DateTime lastWriteTimeUtc = fileInfo.LastWriteTimeUtc;
DateTime lastAccessTimeUtc = fileInfo.LastAccessTimeUtc;

// write file last modification time (local / UTC)
Console.WriteLine(lastWriteTime);     // 9/30/2007 2:16:04 PM
Console.WriteLine(lastWriteTimeUtc);  // 9/30/2007 6:16:04 PM

Explain About RANKING Functions – ROW_NUMBER, RANK, DENSE_RANK, NTILE in SQL

I have not written about this subject for long time, as I strongly believe that Book On Line explains this concept very well. SQL Server 2005 has total of 4 ranking function. Ranking functions return a ranking value for each row in a partition. All the ranking functions are non-deterministic.
ROW_NUMBER () OVER ([<partition_by_clause>] <order_by_clause>)
Returns the sequential number of a row within a partition of a result set, starting at 1 for the first row in each partition.
RANK () OVER ([<partition_by_clause>] <order_by_clause>)
Returns the rank of each row within the partition of a result set.
DENSE_RANK () OVER ([<partition_by_clause>] <order_by_clause>)
Returns the rank of rows within the partition of a result set, without any gaps in the ranking.
NTILE (integer_expression) OVER ([<partition_by_clause>] <order_by_clause>)
Distributes the rows in an ordered partition into a specified number of groups.
All the above definition and syntax are taken from BOL. It is difficult to explain above function anything else than what they are explained in BOL. Following example is excellent example from BOL again. This function explains usage of all the four function together in one query.
USE AdventureWorks;
GO
SELECT c.FirstName, c.LastName
,ROW_NUMBER() OVER (
ORDER BY a.PostalCode) AS 'Row Number'
,RANK() OVER (
ORDER BY a.PostalCode) AS 'Rank'
,DENSE_RANK() OVER (
ORDER BY a.PostalCode) AS 'Dense Rank'
,NTILE(4) OVER (
ORDER BY a.PostalCode) AS 'Quartile'
,s.SalesYTD, a.PostalCode
FROM Sales.SalesPerson s
INNER JOIN Person.Contact c
ON s.SalesPersonID = c.ContactID
INNER JOIN Person.Address a
ON a.AddressID = c.ContactID
WHERE TerritoryID IS NOT NULL
AND
SalesYTD <> 0;

Resultset:

Creating MSI or EXE for Asp.Net WebApplication

Steps:
1.Open Visual studio New--> project.
2.Select Setup and deployment in left side and Web Setup Project in right side pane.Select the Location where to create the setup file and give Name to solution.
3.The application will have the bin file under Web Application Folder,here you have to rename bin into bin1.
4.Copy and Paste File that you have published.
5.After data pasted the folder have bin and bin1 ,delete bin1 folder you re-named .
6.Right click the Web Application Folder select the Properties Window.
7.Set Default Document as Application starting Login page ( Login.aspx ).
8.In Solution Explorer Select User interface Editor.
9.In User Interface Editor ,Select add Dialogue in Start.
10.Select Customer information in Add Dialogue Box and click OK.
11.. By default Customer Information will be at last so move above one step.
12.Select property for Customer Information
13.Serial number template are there , we can create number of possibilities of keyword template

Valid editable characters for the SerialNumberTemplate property are:
Char Meaning
# Requires a digit that will not be included in the validation algorithm.
% Requires a digit that will be included in the validation algorithm.
? Requires an alphanumeric character that will not be included in the validation algorithm.
^ Requires an uppercase or lowercase character. Numeric digits are not valid here.
< Any characters to the left of this character will not be visible in the dialog box.
> Any characters to the right of this character will not be visible in the dialog box. Required as a terminator if the < character is used.

Any other character is treated as a literal constant.


For example, setting the SerialNumberTemplate property to "<### - %%%%>" creates two text boxes separated by a dash surrounded by spaces. Validation for the first box (###) simply verifies that the user has entered three digits. The second box (%%%%) is validated by an algorithm that adds the digits together and divides the sum by 7. If the remainder is 0, validation succeeds; otherwise, it fails.
 
Example
                  ????? - %%%%% - ????? - ????? - ?????
 You could still use a mix of numbers and letters in your keys, but the second box would always contain numbers - i.e. "BC45T - 340707 - 1XFFE - EFT22 - 1XYZ3


14.Set Show Serial Number properties to True.
15.Build the Process
16.Go to the Local folder where the project created and copy the .msi Extension file and install the application