File operations in C# (.net)


Here we are performing some basic file operations which widely needed in applications.

ASPX :

    <div>
        <asp:Button ID="Button1" runat="server" Text="CLick" onclick="Button1_Click" />
        <asp:FileUpload ID="FileUpload1" runat="server" /><br /><br />     
    </div>

C# :
       using System.IO;
       using System.Text;


        protected void Button1_Click(object sender, EventArgs e)
        {

            string path = @"E:\MVC Application Demos\ABC.txt";            // File Path taken

            string name = FileUpload1.FileName.ToString();                // Here we get File Name only

            string path1 = FileUpload1.PostedFile.FileName.ToString();    // Here we get File Path only

            if (File.Exists(path.ToString()))
            {          
           //     ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('File Already exists');", true);
            }
            else
            {
              // Create File Code
            }

            /*  Write File , which stored @remote location  */
            using (FileStream fs = File.Create(path, 1024))
            {
                Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");    // Add some information to the file.              
                fs.Write(info, 0, info.Length);
            }



            /* Create a file to write to. */
            using (StreamWriter sw = File.CreateText(path))
            {
                sw.WriteLine("Hello");
                sw.WriteLine("And");
                sw.WriteLine("Welcome");
            }


            /* This text is always added, making the file longer over time
             if it is not deleted. */
            using (StreamWriter sw = File.AppendText(path))
            {
                sw.WriteLine("This");
                sw.WriteLine("is Extra");
                sw.WriteLine("Text");
            }              


            File.SetCreationTime(path, new DateTime(1857, 1, 1));       /* Set creation time of file  */
            File.SetLastAccessTime(path, new DateTime(1985, 5, 4));     /* Set last access time of file  */
            File.SetLastWriteTime(path, new DateTime(1985, 4, 3));      /* Set last write time of file  */   

        }


Reference :

 1)  File Members

 2)  File Methods

Comments

Popular posts from this blog

Add Serial no in crystal report without coding

How to get top " n " number of rows from table