Showing posts with label FILESTREAM. Show all posts
Showing posts with label FILESTREAM. Show all posts

Tuesday, 11 September 2012

Download Sample Application. Download...

Binary Deserialization is a reverse process of Binary Serialization.
In Binary Deserialization we fetch binary file that generated from Binary Serialization and get back orignal object.
In previous example we serialize one list object using binary serialization and store in file.

Here is example for this.
In this example we take binary serialized file and generate list object from that with data.
You can see in the output image that "booklist" object fill from the "books.bin" binary file.

C# Examples :
    [Serializable]
    public class Books
    {
        public string Title { get; set; }
        public string ISBN { get; set; }
        public DateTime ReleaseDate { get; set; }
        public int Pages { get; set; }
        public int PublisherId { get; set; }
    }
       
   
    protected void Page_Load(object sender, EventArgs e)
    {
        //Read Binary Serialized File
        System.IO.FileStream objFS = System.IO.File.OpenRead(Server.MapPath("books.bin"));
        BinaryFormatter objBF = new BinaryFormatter();
        // Deserialize File stream into object
        var bookslist = objBF.Deserialize(objFS);

    }
VB.net Examples :
    <Serializable()> _
    Public Class Books
        Public Property Title() As String
        Public Property ISBN As String
        Public Property ReleaseDate As Date
        Public Property Pages As Integer
        Public Property PublisherId As Integer
    End Class

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        ''Read Binary Serialized File
        Dim objFS As System.IO.FileStream = System.IO.File.OpenRead(Server.MapPath("books.bin"))
        Dim objBF As New BinaryFormatter()
        '' Deserialize File stream into object
        Dim bookslist = objBF.Deserialize(objFS)
    End Sub

Output : 

(To view original image , click on image)


Click Here to view "Serialize object and store in file using Binary Serialization with C# Examples and VB.Net Examples". Click Here...

This is very useful .Net Tips.

For Beginning .Net articles. Click Here...

To learn more regarding XML. Click Here...

Note : Give Us your valuable feedback in comments. Give your suggestions in this article so we can update our articles accordingly that.



Monday, 10 September 2012

 Download Sample Application. Download...

There is a need to serialize object and store into a file, and then deserialize when required.
For Binary Serialization we are using "BinaryFormatter" class which is available in "System.Runtime.Serialization.Formatters.Binary" namespace.
"BinaryFormatter" class produce a binary data of serialized object. If you want to serialize custom class object for that you have to declare that class as serializable and add "[Serializable]" attribute on that class name.

Here is example for this.
In this example we take one class name "Books" and generate books list object and do binary serialize of that list and store in "Books.bin" file. You can give any extension of that generated file name. The generated file is in binary so not easy to understand.


C# Examples :
    [Serializable]
    public class Books
    {
        public string Title { get; set; }
        public string ISBN { get; set; }
        public DateTime ReleaseDate { get; set; }
        public int Pages { get; set; }
        public int PublisherId { get; set; }
    }

    public List<Books> GetBooksList()
    {
        return new List<Books> {
                        new Books { Title="ASP.NET",ISBN="asp1",ReleaseDate= DateTime.Parse( "11/11/2010") ,Pages=200,PublisherId=1},
                        new Books { Title="C#.NET",ISBN="c#2",ReleaseDate= DateTime.Parse( "10/11/2010") ,Pages=500,PublisherId=1},
                        new Books { Title="VB.NET",ISBN="vb3",ReleaseDate= DateTime.Parse( "5/5/2009") ,Pages=400,PublisherId=1},
                        new Books { Title="SQL Server",ISBN="sql4",ReleaseDate= DateTime.Parse( "6/9/2010"),Pages=300,PublisherId=2 },
                        new Books { Title="JAVA",ISBN="java5",ReleaseDate= DateTime.Parse( "8/5/2011"),Pages=400,PublisherId=3 },
                        new Books { Title="HTML",ISBN="html6",ReleaseDate= DateTime.Parse( "9/5/2011"),Pages=400 }
        
        };

    }

    private void BinarySerialization(System.Collections.Generic.List<Books> bookslist)
    {
        BinaryFormatter objBF = new BinaryFormatter();
        System.IO.FileStream objFS = System.IO.File.Create(Server.MapPath("books.bin"));
        objBF.Serialize(objFS, bookslist);
        objBF = null;
        objFS.Close();
        objFS = null;
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        System.Collections.Generic.List<Books> bookslist = GetBooksList();
        BinarySerialization(bookslist);
    }

VB.net Examples :
    <Serializable()> _
    Public Class Books
        Public Property Title() As String
        Public Property ISBN As String
        Public Property ReleaseDate As Date
        Public Property Pages As Integer
        Public Property PublisherId As Integer
    End Class

    Public Function GetBooksList() As List(Of Books)
        Dim lstBooks As New List(Of Books) From { _
                                New Books With {.Title = "ASP.NET", .ISBN = "asp1", .ReleaseDate = DateTime.Parse("11/11/2010"), .Pages = 200, .PublisherId = 1}, _
                                New Books With {.Title = "C#.NET", .ISBN = "c#2", .ReleaseDate = DateTime.Parse("10/11/2010"), .Pages = 500, .PublisherId = 1}, _
                                New Books With {.Title = "VB.NET", .ISBN = "vb3", .ReleaseDate = DateTime.Parse("5/5/2009"), .Pages = 400, .PublisherId = 1}, _
                                New Books With {.Title = "SQL Server", .ISBN = "sql4", .ReleaseDate = DateTime.Parse("6/9/2010"), .Pages = 300, .PublisherId = 2}, _
                                New Books With {.Title = "JAVA", .ISBN = "java5", .ReleaseDate = DateTime.Parse("8/5/2011"), .Pages = 400, .PublisherId = 3}, _
                                New Books With {.Title = "HTML", .ISBN = "html6", .ReleaseDate = DateTime.Parse("9/5/2011"), .Pages = 400}}

        Return lstBooks
    End Function

    Private Sub BinarySerialization(ByVal bookslist As System.Collections.Generic.List(Of Books))
        Dim objBF As New BinaryFormatter()
        Dim objFS As System.IO.FileStream = System.IO.File.Create(Server.MapPath("books.bin"))
        objBF.Serialize(objFS, bookslist)
        objBF = Nothing
        objFS.Close()
        objFS = Nothing
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim bookslist As System.Collections.Generic.List(Of Books) = GetBooksList()
        BinarySerialization(bookslist)
    End Sub

Output : 

(To view original image , click on image)


Click Here to view "Binary Deserialization with C# Examples and VB.Net Examples". Click Here...

This is very useful .Net Tips.

For Beginning .Net articles. Click Here...


Note : Give Us your valuable feedback in comments. Give your suggestions in this article so we can update our articles accordingly that.




Monday, 23 July 2012

.NET Framework 4 introduce new "CopyTo" method of Stream Class of System.IO namespace. Using this method we can copy one stream to another stream of different stream class.
You can also say that write content or data of one stream to another stream.

Here is example of this.
In this example we copy FileStream content to MemoryStream. We first create file stream object and print it's length after that we copy filestream object to memorystrem object and print it's length. You can see output in below image.

C# Example :
        FileStream objFileStream = File.Open(Server.MapPath("TextFile.txt"), FileMode.Open);
        Response.Write(string.Format("FileStream Content length: {0}", objFileStream.Length.ToString()));

        MemoryStream objMemoryStream = new MemoryStream();

        // Copy File Stream to Memory Stream using CopyTo method
        objFileStream.CopyTo(objMemoryStream);
        Response.Write("<br/><br/>");
        Response.Write(string.Format("MemoryStream Content length: {0}", objMemoryStream.Length.ToString()));
        Response.Write("<br/><br/>");

VB.net Example :
        Dim objFileStream As FileStream = File.Open(Server.MapPath("TextFile.txt"), FileMode.Open)
        Response.Write(String.Format("FileStream Content length: {0}", objFileStream.Length.ToString()))

        Dim objMemoryStream As New MemoryStream()

        ' Copy File Stream to Memory Stream using CopyTo method
        objFileStream.CopyTo(objMemoryStream)
        Response.Write("<br/><br/>")
        Response.Write(String.Format("MemoryStream Content length: {0}", objMemoryStream.Length.ToString()))
        Response.Write("<br/><br/>")
Output :



This type of C# Tips is very useful in day to day programming life.

Note : Give Us your valuable feedback in comments. Give your suggestions in this article so we can update our articles accordingly that.


Tuesday, 19 June 2012

You can open a file in read mode and get FileStream Object for reading a stream.
After getting FileStream object you can read data using "Read" and "ReadByte" methods.
You can open any file i.e Text , Image , doc etc..
After reading the file you need to close the FileStream Object.

Here are example for this.
In this example we open two different "Text" and "Image" format files.

C# Example :
    // Get a filestream for reading a Text file
    System.IO.FileStream objFileStreamTxt = System.IO.File.OpenRead(MapPath("TextFile.txt"));
    objFileStreamTxt.Close();

    // Get a filestream for reading a Image file
    System.IO.FileStream objFileStreamImg = System.IO.File.OpenRead(MapPath("computer.jpg"));
    objFileStreamImg.Close();

VB.net Example :
        ' Get a filestream for reading a Text file
        Dim objFileStreamTxt As System.IO.FileStream = System.IO.File.OpenRead(MapPath("TextFile.txt"))
        objFileStreamTxt.Close()

        ' Get a filestream for reading a Image file
        Dim objFileStreamImg As System.IO.FileStream = System.IO.File.OpenRead(MapPath("computer.jpg"))
        objFileStreamImg.Close()

Here is example of how to read FileStream object using "Read" method. Click Here...

This is very useful .Net Tips which is use in day to day programming life.

You can read file byte data using "Read" Method of FileStream class and get bytes array. You can also say that read bytes array from FileStream object or read bytes array from FILE.

Here are example of this.
In this example We get FileStream of file and read it's byte data , byte data are store in Byte array.
You can also say that this approach is as chunk by chunk reading.

C# Example :
    // Get a filestream for reading a Text file
    System.IO.FileStream objFileStreamTxt = System.IO.File.OpenRead(MapPath("TextFile.txt"));

    // Set buffer length
    int intBufferLength = 16 * 1024;
    byte[] objBuffer = new byte[intBufferLength];

    int len = 0;

    while ((len = objFileStreamTxt.Read(objBuffer, 0, intBufferLength)) != 0)
    {
        // Here objBuffer object has bytes value, Which you can use to write into other stream or other use
        // Here objBuffer object contains intBufferLength length data
    }

    objFileStreamTxt.Close();

VB.net Example :
        ' Get a filestream for reading a Text file
        Dim objFileStreamTxt As System.IO.FileStream = System.IO.File.OpenRead(MapPath("TextFile.txt"))

        ' Set buffer length
        Dim intBufferLength As Integer = 16 * 1024
        Dim objBuffer As Byte() = New Byte(intBufferLength - 1) {}

        Dim len As Integer = 0
        len = objFileStreamTxt.Read(objBuffer, 0, intBufferLength)
        While len <> 0
            ' Here objBuffer object has bytes value, Which you can use to write into other stream or other use
            ' Here objBuffer object contains intBufferLength length data
            len = objFileStreamTxt.Read(objBuffer, 0, intBufferLength)
        End While

        objFileStreamTxt.Close()

In this example we read bytes array chunk by chunk , but If you want to get all bytes value whithout using loop than use this code.

C# Example (Without Loop) :
    System.IO.FileStream objFileStreamTmp = System.IO.File.OpenRead(MapPath("TextFile.txt"));
    byte[] objBufferTmp = new byte[objFileStreamTmp.Length];
    len = objFileStreamTmp.Read(objBufferTmp, 0, objBufferTmp.Length);

    objFileStreamTmp.Close();

VB.net Example (Without Loop) :
        Dim objFileStreamTmp As System.IO.FileStream = System.IO.File.OpenRead(MapPath("TextFile.txt"))
        Dim objBufferTmp As Byte() = New Byte(objFileStreamTmp.Length - 1) {}
        len = objFileStreamTmp.Read(objBufferTmp, 0, objBufferTmp.Length)

        objFileStreamTmp.Close()

Note : The chunk by chunk means looping approach is very good when you open a large file. Because if you open a large file in one statement it may gives Memory related errors.

This is very useful .Net Tips which is use in day to day programming life.


Saturday, 16 June 2012

There is a very quick way in .Net to read the entire file and return a string of data.
We are using ReadAllText method of File class.
Here are sample example of this.
In this example we read the whole file in one statement and return it's string of data.
These examples are in both C# and VB.Net .

C# Example :
 // Read the entire file and returns a string of data
 string strData = System.IO.File.ReadAllText(MapPath("TextFile.txt"));

VB.net Example :
'' Read the entire file and returns a string of data
Dim strData As String = System.IO.File.ReadAllText(MapPath("TextFile.txt"))

This is very useful .Net Tips which is use in day to day programming life.


Thursday, 14 June 2012

There is a very quick way to open text file and appends data into that file.
There are two methods to appends text files AppendAllText and AppendAllLines.
These methods open a file. Appends data to the files , and then close the file. If file does not exist, These methods create the files , appends the data and close the file.

If you do not want append the data but you want overwrite the data of file you can also do this with the help of WriteAllText and WriteAllLines Methods.
These methods create the file and write data in file, If file is already exists than this will overwrite data.

Here are sample example of this.
In this example For append we are using AppendAllText method for directly append sample string.
and  AppendAllLines method to append IEnumerable of strings.
For write we are using WriteAllText method to write data in file and WriteAllLines method to write IEnumerable of strings.

C# Example :
    string strData = "This is sample string.";

    string[] lineNumbers = (from line in System.IO.File.ReadLines(MapPath("TextFile.txt"))
                            where line.Contains("sample")
                            select line).ToArray();

    // Appends the string of data to a file
    System.IO.File.AppendAllText(MapPath("TextFile1.txt"), strData);
    //Appends the IEnumerable of strings to a text file
    System.IO.File.AppendAllLines(MapPath("TextFile1.txt"), lineNumbers);

    // Writes the string of data to a file
    System.IO.File.WriteAllText(MapPath("TextFile2.txt"), strData);

    // Writes an IEnumerable of strings to a text file
    System.IO.File.WriteAllLines(MapPath("TextFile2.txt"), lineNumbers);

VB.net Example :
        Dim strData As String = "This is sample string."

        Dim lineNumbers As String() = (From line In System.IO.File.ReadLines(MapPath("TextFile.txt"))
                                      Where line.Contains("sample")
                                      Select line).ToArray()

        ' Appends the string of data to a file
        System.IO.File.AppendAllText(MapPath("TextFile1.txt"), strData)
        'Appends the IEnumerable of strings to a text file
        System.IO.File.AppendAllLines(MapPath("TextFile1.txt"), lineNumbers)

        ' Writes the string of data to a file
        System.IO.File.WriteAllText(MapPath("TextFile2.txt"), strData)

        ' Writes an IEnumerable of strings to a text file
        System.IO.File.WriteAllLines(MapPath("TextFile2.txt"), lineNumbers)

This is very useful .Net Tips which is use in day to day programming life.


Wednesday, 13 June 2012

.Net framework provide the System.IO.Compression.GZipStream or System.IO.Compression.DeflateStream to compress or decompress data.
Both GZipStream and DeflateStream classes allow you to use GZIP and Deflate compression algorithms to compress or decompress data.

Here are sample examples with GZipStream class.
The sample examples there are two methods one is CompressData and other is DCompressData.
In CompressData method we create a new file and uses the GZipStream class to write compressed file to it and close that file .
In DCompressData method we open that compressed file in read mode and decompressed the file and save.
In this sample you have to provide the file path which file you want to compress and also provide file path where the compressed file stored.
In this example we store both files in application root directory.

This examples are in both C# and VB.Net .

C# Example :
    protected void Page_Load(object sender, EventArgs e)
    {

        CompressData();
        DCompressData();
             
    }
    void CompressData()
    {
        // Create the compression stream.
        GZipStream objGZipOut = new GZipStream(File.OpenWrite(Server.MapPath("compressed_data.gzip")), CompressionMode.Compress);
        
        int intBufferLength = 16 * 1024;
        byte[] objBuffer = new byte[intBufferLength];

        // Get File Stream Object
        System.IO.FileStream objFileStream = System.IO.File.Open(MapPath("TextFile.txt"), System.IO.FileMode.Open);
        int len = 0;

        while ((len = objFileStream.Read(objBuffer, 0, intBufferLength)) != 0)
        {
            // Write file Content 
            objGZipOut.Write(objBuffer, 0, len);

        }
        objFileStream.Close();
        objGZipOut.Close();
       
    }
    void DCompressData()
    {
        // Open the same gzip file to decompress
        GZipStream objGZipIn = new GZipStream(File.OpenRead(Server.MapPath("compressed_data.gzip")), CompressionMode.Decompress);

        // Get stream reader of the gzip file.
        StreamReader objReader = new StreamReader(objGZipIn);
       
        byte[] buffer = new byte[16 * 1024];
        int len = 0;
        FileStream objFS = new FileStream(Server.MapPath("compressed_data.txt"), FileMode.Create, FileAccess.Write, FileShare.Read);
        while ((len = objReader.BaseStream.Read(buffer, 0, buffer.Length)) != 0)
        {
            objFS.Write(buffer, 0, len);
        }
        objFS.Close();
        objReader.Close();
        objGZipIn.Close();
       
    }


VB.net Example :
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        CompressData()
        DCompressData()
    End Sub
    Private Sub CompressData()
        ' Create the compression stream.
        Dim objGZipOut As New GZipStream(File.OpenWrite(Server.MapPath("compressed_data.gzip")), CompressionMode.Compress)

        Dim intBufferLength As Integer = 16 * 1  '1024
        Dim objBuffer As Byte() = New Byte(intBufferLength - 1) {}

        ' Get File Stream Object
        Dim objFileStream As System.IO.FileStream = System.IO.File.Open(MapPath("TextFile.txt"), System.IO.FileMode.Open)
        Dim len As Integer = 0
        len = objFileStream.Read(objBuffer, 0, intBufferLength)
        While len <> 0
            ' Write file Content 
            objGZipOut.Write(objBuffer, 0, len)
            len = objFileStream.Read(objBuffer, 0, intBufferLength)
        End While

        objFileStream.Close()
        objGZipOut.Close()

    End Sub
    Private Sub DCompressData()
        ' Open the same gzip file to decompress
        Dim objGZipIn As New GZipStream(File.OpenRead(Server.MapPath("compressed_data.gzip")), CompressionMode.Decompress)

        ' Get stream reader of the gzip file.
        Dim objReader As New StreamReader(objGZipIn)

        Dim buffer As Byte() = New Byte(16 * 1024 - 1) {}
        Dim len As Integer = 0
        Dim objFS As New FileStream(Server.MapPath("compressed_data.txt"), FileMode.Create, FileAccess.Write, FileShare.Read)
        len = objReader.BaseStream.Read(buffer, 0, buffer.Length)
        While len <> 0
            objFS.Write(buffer, 0, len)
            len = objReader.BaseStream.Read(buffer, 0, buffer.Length)
        End While
        
        objFS.Close()
        objReader.Close()
        objGZipIn.Close()

    End Sub

You can also provide other data like simple string to compress data , for that you have to use stream writer and use it's WriteLine method.

In this example we provide "TextFile.txt" text file. Size of this text file is 3 kb.
After the compressing new file "compressed_data.gzip" generated and it's size is 1 kb.

Output :

Before compression 



After compression 



Tuesday, 12 June 2012

You can also query the text file using LINQ .
Here are example for this.
In this example we can get specific lines which has matching word given by us.
After the LINQ query is executed you need to close file otherwise it gives error on next attempt to access of file.

C# Example :
string[] lineNumbers = (from line in
                        System.IO.File.ReadLines(MapPath(
                        where line.Contains("sample")
                        select line).ToArray();

System.IO.File.OpenText(MapPath("TextFile.txt")).Close();

VB.net Example :
Dim lineNumbers As String() = (From line In
                              System.IO.File.ReadLines(MapPath("TextFile.txt"))
                              Where line.Contains("sample")
                              Select line).ToArray()

System.IO.File.OpenText(MapPath("TextFile.txt")).Close()

Monday, 11 June 2012

You are able to get stream reader of a file and work on stream reader.
After getting Stream Reader and completing work on stream reader you have to close SteramReader using Close method. to avoid any file open errors.

Here are example for this.

C# Example :
System.IO.StreamReader objStreamReader = System.IO.File.OpenText(MapPath("TextFile.txt"));
objStreamReader.Close();

VB.net Example :
Dim objStreamReader As System.IO.StreamReader = System.IO.File.OpenText(MapPath("TextFile.txt"))
objStreamReader.Close()

Here in below image you can see that after FileStream Object is filled it's properties are set.

Output :

Friday, 8 June 2012

You can get the FileStream of a file by opening a file using File Class.
After get FileStream and completing work on file stream you have to close FileSteram using Close method. to avoid any file open errors.

Here are example for this.
C# Example :
System.IO.FileStream stream1 = System.IO.File.Open(MapPath("TextFile.txt"), System.IO.FileMode.Open);
stream1.Close();

VB.net Example :
Dim stream1 As System.IO.FileStream = System.IO.File.Open(MapPath("TextFile.txt"), System.IO.FileMode.Open)
stream1.Close()

Here in below image you can see that after FileStream Object is filled it's properties are set.

Output :

Tuesday, 15 May 2012

You are able to upload a file on FTP server from your application.
Using FtpWebRequest and FtpWebResponse classes executing File Transfer Protocol (FTP) commands from your Web page easy.
In this example we are using System.Net and System.IO namespaces.
Here is exmple for how to upload file on FTP server.

C# Example :
string filename = Server.MapPath("file1.txt");
string ftpServerIP = "ftp.demo.com/";
string ftpUserName = "dummy";
string ftpPassword = "dummy";

FileInfo objFile = new FileInfo(filename);
FtpWebRequest objFTPRequest;

// Create FtpWebRequest object 
objFTPRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + objFile.Name));

// Set Credintials
objFTPRequest.Credentials = new NetworkCredential(ftpUserName, ftpPassword);

// By default KeepAlive is true, where the control connection is 
// not closed after a command is executed.
objFTPRequest.KeepAlive = false;

// Set the data transfer type.
objFTPRequest.UseBinary = true;

// Set content length
objFTPRequest.ContentLength = objFile.Length;

// Set request method
objFTPRequest.Method = WebRequestMethods.Ftp.UploadFile;

// Set buffer size
int intBufferLength = 16 * 1024;
byte[] objBuffer = new byte[intBufferLength];
        
// Opens a file to read
FileStream objFileStream = objFile.OpenRead();

try
{
    // Get Stream of the file
    Stream objStream = objFTPRequest.GetRequestStream();

    int len = 0;

    while ((len = objFileStream.Read(objBuffer, 0, intBufferLength)) != 0)
    {
        // Write file Content 
        objStream.Write(objBuffer, 0, len);
                
    }
                        
    objStream.Close();
    objFileStream.Close();
}
catch (Exception ex)
{
    throw ex;
}

In this example set appropriate Server and Set credentials if required.

VB.net Example :
Dim filename As String = Server.MapPath("file1.txt")
Dim ftpServerIP As String = "ftp.demo.com/"
Dim ftpUserName As String = "dummy"
Dim ftpPassword As String = "dummy"

Dim objFile As New FileInfo(filename)
Dim objFTPRequest As FtpWebRequest

' Create FtpWebRequest object 
objFTPRequest = DirectCast(FtpWebRequest.Create(New Uri(("ftp://" & ftpServerIP & "/") + objFile.Name)), FtpWebRequest)

' Set Credintials
objFTPRequest.Credentials = New NetworkCredential(ftpUserName, ftpPassword)

' By default KeepAlive is true, where the control connection is 
' not closed after a command is executed.
objFTPRequest.KeepAlive = False

' Set the data transfer type.
objFTPRequest.UseBinary = True

' Set content length
objFTPRequest.ContentLength = objFile.Length

' Set request method
objFTPRequest.Method = WebRequestMethods.Ftp.UploadFile

' Set buffer size
Dim intBufferLength As Integer = 16 * 1024
Dim objBuffer As Byte() = New Byte(intBufferLength - 1) {}

' Opens a file to read
Dim objFileStream As FileStream = objFile.OpenRead()

Try
    ' Get Stream of the file
    Dim objStream As Stream = objFTPRequest.GetRequestStream()

    Dim len As Integer = 0

    len = objFileStream.Read(objBuffer, 0, intBufferLength)
    While len <> 0
         ' Write file Content 
         objStream.Write(objBuffer, 0, len)
         len = objFileStream.Read(objBuffer, 0, intBufferLength)
    End While
    objStream.Close()
    objFileStream.Close()
Catch ex As Exception
    Throw ex
End Try

Monday, 14 May 2012

You are able to download file from FTP server and save to your desire location using .Net
Using FtpWebRequest and FtpWebResponse classes executing File Transfer Protocol (FTP) commands from your Web page easy. Using these classes, implementing an entire FTP client right from your Web application is now possible.
In this example we are using System.Net and System.IO namespaces.

C# Example :
Uri url = new Uri("ftp://ftp.demo.com/file1.txt");
if (url.Scheme == Uri.UriSchemeFtp)
{
    FtpWebRequest objRequest = (FtpWebRequest)FtpWebRequest.Create(url);
    //Set credentials if required else comment this Credential code
    NetworkCredential objCredential = new NetworkCredential("FTPUserName", "FTPPassword");
    objRequest.Credentials = objCredential;
    objRequest.Method = WebRequestMethods.Ftp.DownloadFile;
    FtpWebResponse objResponse = (FtpWebResponse)objRequest.GetResponse();
    StreamReader objReader = new StreamReader(objResponse.GetResponseStream());
    byte[] buffer = new byte[16 * 1024];
    int len = 0;
    FileStream objFS = new FileStream(Server.MapPath("file1.txt"), FileMode.Create, FileAccess.Write, FileShare.Read);
    while ((len = objReader.BaseStream.Read(buffer, 0, buffer.Length)) != 0)
    {
        objFS.Write(buffer, 0, len);
    }
    objFS.Close();
    objResponse.Close();
}
In this example put your URI appropriate and Set credentials if required.

VB.net Example :
Dim url As New Uri("ftp://ftp.demo.com/file1.txt")
If url.Scheme = Uri.UriSchemeFtp Then
    Dim objRequest As FtpWebRequest = DirectCast(FtpWebRequest.Create(url), FtpWebRequest)
    'Set credentials if required else comment this Credential code
    Dim objCredential As New NetworkCredential("FTPUserName", "FTPPassword")
    objRequest.Credentials = objCredential
    objRequest.Method = WebRequestMethods.Ftp.DownloadFile
    Dim objResponse As FtpWebResponse = DirectCast(objRequest.GetResponse(), FtpWebResponse)
    Dim objReader As New StreamReader(objResponse.GetResponseStream())
    Dim buffer As Byte() = New Byte(16 * 1024 - 1) {}
    Dim len As Integer = 0
    Dim objFS As New FileStream(Server.MapPath("file1.txt"), FileMode.Create, FileAccess.Write, FileShare.Read)
    len = objReader.BaseStream.Read(buffer, 0, buffer.Length)
    While len <> 0
         objFS.Write(buffer, 0, len)
         len = objReader.BaseStream.Read(buffer, 0, buffer.Length)
    End While
    objFS.Close()
    objResponse.Close()
End If

Friday, 11 May 2012

There are situations where you want to post data to remote server and other external URL.
We can do this using System.Net namespace.
In this sample example we have this "http://www.dummydomain.com/pagename.aspx" URL and we want to post query string data like "pageid=1&search=.net" and capture response of this in our code.
We are using HttpWebRequest and HttpWebResponse class for this.


C# Example :
Uri url = new Uri("http://www.dummydomain.com/pagename.aspx");
string strParameter = "pageid=1&search=.net";
string data = string.Format("{0}", strParameter);
if (url.Scheme == Uri.UriSchemeHttp)
{
    //Create Request for given url
    System.Net.HttpWebRequest objRequest =(System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
    //Set Request Method
    objRequest.Method = System.Net.WebRequestMethods.Http.Post;
    objRequest.ContentLength = data.Length;
    objRequest.ContentType = "application/x-www-form-urlencoded";
    //Write request stream
    System.IO.StreamWriter objWriter = new System.IO.StreamWriter(objRequest.GetRequestStream());
    objWriter.Write(data);
    objWriter.Close();
    //Get Response from url
    System.Net.HttpWebResponse objResponse = (System.Net.HttpWebResponse)objRequest.GetResponse();
    //Read Response
    System.IO.StreamReader objReader = new System.IO.StreamReader(objResponse.GetResponseStream());
    string result = objReader.ReadToEnd();
    objResponse.Close();
    pnlScreen.GroupingText = result;
}

VB.net Example :
Dim url As New Uri("http://www.dummydomain.com/pagename.aspx")
Dim strParameter As String = "pageid=1&search=.net"
Dim data As String = String.Format("{0}", strParameter)
If url.Scheme = Uri.UriSchemeHttp Then
    'Create Request for given url
    Dim objRequest As System.Net.HttpWebRequest = DirectCast(System.Net.HttpWebRequest.Create(url), System.Net.HttpWebRequest)
    'Set Request Method
    objRequest.Method = System.Net.WebRequestMethods.Http.Post
    objRequest.ContentLength = data.Length
    objRequest.ContentType = "application/x-www-form-urlencoded"
    'Write request stream
    Dim objWriter As New System.IO.StreamWriter(objRequest.GetRequestStream())
    objWriter.Write(data)
    objWriter.Close()
    'Get Response from url
    Dim objResponse As System.Net.HttpWebResponse = DirectCast(objRequest.GetResponse(), System.Net.HttpWebResponse)
    'Read Response
    Dim objReader As New System.IO.StreamReader(objResponse.GetResponseStream())
    Dim result As String = objReader.ReadToEnd()
    objResponse.Close()
    pnlScreen.GroupingText = result
End If

Thursday, 10 May 2012

Screen scrapping means to get other sites data from given URL.
You can do this using the HttpWebRequest and HttpWebResponse classes to screen scrape, you can use the following code to build a Web page that will serve as a simple Web browser. You also learn how to display another Web page inside of yours using an HttpWebRequest. In this example, you scrape the "http://msdn.microsoft.com/en-US/" URL and display it in a panel on your Web page.
For this example we are using System.Net and System.IO Namespaces.

ASPX Code : 
 <asp:Panel runat="server" ID="pnlScreen" ScrollBars=Auto
Width="800px" Height="500px"></asp:Panel>

C# Example :
Uri url = new Uri("http://msdn.microsoft.com/en-US/");
if (url.Scheme == Uri.UriSchemeHttp)
{
    //Create Request Object
    HttpWebRequest objRequest = (HttpWebRequest)HttpWebRequest.Create(url);
    //Set Request Method
    objRequest.Method = WebRequestMethods.Http.Get;
    //Get response from requested url
    HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
    //Read response in stream reader
    StreamReader reader = new StreamReader(objResponse.GetResponseStream());
    string tmp = reader.ReadToEnd();
    objResponse.Close();
    //Set response data to container
    this.pnlScreen.GroupingText = tmp;
}

The HttpWebRequest to the "http://msdn.microsoft.com/en-US/" page returns a string containing the scraped HTML. The sample assigns the value of this string to the GroupingText property of the Panel control. When the final page is rendered, the browser renders the HTML that was scraped as literal content on the page.

VB.net Example :
Dim url As New Uri("http://msdn.microsoft.com/en-US/")
If url.Scheme = Uri.UriSchemeHttp Then
    'Create Request Object
    Dim objRequest As HttpWebRequest = DirectCast(HttpWebRequest.Create(url), HttpWebRequest)
    'Set Request Method
    objRequest.Method = WebRequestMethods.Http.[Get]
    'Get response from requested url
    Dim objResponse As HttpWebResponse = DirectCast(objRequest.GetResponse(), HttpWebResponse)
    'Read response in stream reader
    Dim reader As New StreamReader(objResponse.GetResponseStream())
    Dim tmp As String = reader.ReadToEnd()
    objResponse.Close()
    'Set response data to container
    Me.pnlScreen.GroupingText = tmp
End If
Output :
(To view original image , click on image)

Wednesday, 9 May 2012

Using streams does have a couple problems that might encounter in certain scenarios.
  1. When you open a file using a stream, reading the file contents is done sequentially. This can be a problem if you are searching for a specific section of a very large file because you have to read the entire file from the beginning in order to locate the content.
  2. Opening a file using a stream can lock the file, preventing other applications or threads from reading or writing to the file.

.NET Framework includes the System.IO.MemoryMappedFiles namespace, which includes a number of classes that allow you to create memory-mapped files. Memory-mapped files can be useful when you encounter the limitations of the stream objects.

Memory-mapped files allow to create views that start in a random location over very large files, rather than reading the file from the beginning. Memory-mapped files also allow multiple processes to map to the same portion of a file without locking the file.

C# Example :
byte[] bytes = new byte[100];
using (System.IO.MemoryMappedFiles.MemoryMappedFile objMF = System.IO.MemoryMappedFiles.MemoryMappedFile.CreateFromFile(MapPath("TextFile.txt"), System.IO.FileMode.Open, "NewTextFile"))
{
    using (System.IO.MemoryMappedFiles.MemoryMappedViewAccessor accessor = objMF.CreateViewAccessor(100, 100))
    {
        accessor.ReadArray(0, bytes, 0, bytes.Length);
    }
}
Response.Write(ASCIIEncoding.Default.GetString(bytes));
This Example loads the TextFile.txt file into a MemoryMappedFile class using the static CreateFromFile method, which creates a named memory-mapped file. It then creates a MemoryMappedViewAccessor over the file using the MemoryMappedFiles CreateViewAccessor method. This method’s parameters allow  to specify an offset where the view accessor should start, the length of the view, and the access rights the view will have to the file.

The MemoryMappedFile class also allows to create memory-mapped files that are not associated with a physical file on disk, but are rather simply a named portion of memory. You can do this using the class’s static CreateNew method, which accepts a name and a length parameter.

VB.net Example :
Dim bytes As Byte() = New Byte(99) {}
    Using objMF As System.IO.MemoryMappedFiles.MemoryMappedFile = System.IO.MemoryMappedFiles.MemoryMappedFile.CreateFromFile(MapPath("TextFile.txt"), System.IO.FileMode.Open, "NewTextFile")
        Using accessor As System.IO.MemoryMappedFiles.MemoryMappedViewAccessor = objMF.CreateViewAccessor(100, 100)
            accessor.ReadArray(0, bytes, 0, bytes.Length)
        End Using
    End Using
Response.Write(ASCIIEncoding.[Default].GetString(bytes))

Friday, 4 May 2012

Main parts of I/O in the .NET Framework are Reader and Writer classes. These classes help the reading and writing of individual bytes to and from Streams.
The .NET Framework provides a wide variety of reader and writer classes, each designed for reading or writing according to a specific set of rules.
Following Table shows a partial list of the readers available in the .NET Framework and the corresponding writer classes.

CLASS DESCRIPTION
System.IO.TextReader Abstract class that enables the reading of a sequential series of characters.
System.IO.StreamReader Reads characters from a byte stream. Derived from TextReader.
System.IO.StringReader Reads textual information as a stream of in-memory characters. Derived from TextReader.
System.IO.BinaryReader Reads primitive data types as binary values from a stream.
System.Xml.XmlTextReader Provides fast, non-cached, forward-only access to XML.
System.IO.TextWriter Abstract class that enables the writing of a sequential series of characters.
System.IO.StreamWriter Writes characters to a stream. Derived from TextWriter.
System.IO.StringWriter Writes textual information as a stream of in-memory characters. Derived from TextWriter.
System.IO.BinaryWriter Writes primitive data types in binary to a stream.
System.Xml.XmlTextWriter Provides a fast, non-cached, forward-only way of generating XML streams or files.

Here are links for sample examples of how the readers and writers abstract reading and writing data. 

Saturday, 28 April 2012

Now use the BinaryReader and BinaryWriter classes to read and write primitive types to a file.The BinaryWriter writes primitive objects in their native format, so in order to read them using the BinaryReader, you must select the appropriate Read method.
The Example shows you how to do that; in this case, you are writing a value from a number of different primitive types to the text file and then reading the same value.

Here are sample Example :

C# Example :
        ///////Write to a file
        System.IO.BinaryWriter binarywriter =new System.IO.BinaryWriter(System.IO.File.Create(MapPath
 ("BinaryFile.dat")));
        binarywriter.Write("This is a sample string.");
        binarywriter.Write(0x12346789abcdef);
        binarywriter.Write(0x12345678);
        binarywriter.Write('c');
        binarywriter.Write(1.5f);
        binarywriter.Write(1000.2m);
        binarywriter.Close();

        ////////Read from a file
        System.IO.BinaryReader binaryreader = new System.IO.BinaryReader(System.IO.File.Open
(MapPath("BinaryFile.dat"), System.IO.FileMode.Open));
        string strA = binaryreader.ReadString();
        long lngL = binaryreader.ReadInt64();
        int intI = binaryreader.ReadInt32();
        char chrC = binaryreader.ReadChar();
        float fltF = binaryreader.ReadSingle();
        decimal dclD = binaryreader.ReadDecimal();
        binaryreader.Close();


If you open this file in Notepad, you will see that the BinaryWriter has written the nonreadable binary data to the file. The BinaryReader provides a number of different methods for reading various kinds of Primitive types from the stream. In this Example, you use a different Read method for each primitive type that you Write to the file.

VB.net Example :
    Dim binarywriter As New System.IO.BinaryWriter(System.IO.File.Create(MapPath("binary.dat")))
    binarywriter.Write("a string")
    binarywriter.Write(&H12346789ABCDEF)
    binarywriter.Write(&H12345678)
    binarywriter.Write("c"c)
    binarywriter.Write(1.5F)
    binarywriter.Write(100.2D)
    binarywriter.Close()

    Dim binaryreader As New System.IO.BinaryReader(System.IO.File.Open(MapPath
     ("binary.dat"),System.IO.FileMode.Open))
    Dim a As String = binaryreader.ReadString()
    Dim l As Long = binaryreader.ReadInt64()
    Dim i As Integer = binaryreader.ReadInt32()
    Dim c As Char = binaryreader.ReadChar()
    Dim f As Double = binaryreader.ReadSingle()
    Dim d As Decimal = binaryreader.ReadDecimal()
    binaryreader.Close()

Friday, 27 April 2012

StreamReader and StreamWriter classes to write a string to a text file and then read the contents of that text file.

Here are Exmaple for Write and Read File.

C# Example :
         /////Write to a file
        System.IO.StreamWriter streamwriter = new System.IO.StreamWriter(System.IO.File.Open
(MapPath("TextFile.txt"),System.IO.FileMode.OpenOrCreate));
        streamwriter.Write("This is a sample string");
        streamwriter.Close();

        //////Read from a file
        System.IO.StreamReader reader =new System.IO.StreamReader(System.IO.File.Open(MapPath
("TextFile.txt"),System.IO.FileMode.Open));
        string tmp = reader.ReadToEnd();
        reader.Close();


When you create a StreamReader, you must pass an existing stream instance as a constructor
parameter. The reader uses this stream as its underlying data source.
In this sample, you use the File class’s Open method to open a writable FileStream for your StreamWriter.

Also notice that you no longer have to deal with byte arrays. The StreamReader takes care of converting the data to a type that’s more user-friendly than a byte array. In this example, you are using the ReadToEnd method to read the entire stream and convert it to a string.The StreamReader provides a number of different methods for reading data that you can use depending on exactly how you want to read the data, from reading a single character using the Read method, to reading the entire file using the ReadToEnd method.

VB.net Example :
    /////Write to a file
    Dim streamwriter As New System.IO.StreamWriter(System.IO.File.Open(MapPath
                     ("TextFile.txt"),System.IO.FileMode.Open))
    streamwriter.Write("This is a string")
    streamwriter.Close()

    //////Read from a file
    Dim reader As New System.IO.StreamReader(System.IO.File.Open(MapPath
                   ("TextFile.txt"),System.IO.FileMode.Open))
    Dim tmp As String = reader.ReadToEnd()
    reader.Close()

Thursday, 26 April 2012

There is a situation where you want to write data in Memory Stream.
You can write to the stream by encoding a string containing the information you want to write to a byte array and then using the stream’s Write method to write the byte array to the MemoryStreams.
The Close method also calls Flush internally to commit the data to the data store.

Here are sample Example
C# Example :
    byte[] data = System.Text.Encoding.ASCII.GetBytes("This is a sample string");
    System.IO.MemoryStream ms = new System.IO.MemoryStream();
    ms.Write(data, 0, data.Length);
    ms.Close();

VB.net Example :
    Dim data() As Byte = System.Text.Encoding.ASCII.GetBytes("This is a sample string")
    Dim ms As New System.IO.MemoryStream()
    ms.Write(data, 0, data.Length)
    ms.Close()