z
 
:: Home     :: MS Dynamics CRM     :: .Net 1.1     :: .Net 2.0     :: Sharepoint Portal     :: Ajax

  login:        
  passwords:  
 

Resources

Finding Correct Content Managemet System
This list covers the full lifecycle of a content management system, from initially creating the content, through to delivering it to end users...

Workflow Managemet Systems
Workflow management is a crucial component in organizing a variety of business processes so that they benefit the business as a whole and increase profitability...

Using the Power of Content Management Systems
With page editors that resemble a word processor program, adding content with a CMS interface is simple and fun. Most CMS software also allows you to change the location of your content pages and links easily, while the back end processes takes care of updating the links throughout your site...

Content Management Systems (CMS): What They Are And Why We Love Them
In the past, individuals who took interest in having and operating their own websites were burdened with the task of learning HTML, DHTML, and other web-based technologies such as JavaScript and CSS. The only alternative to this was, unfortunately, to pocket the expenses and costs required to pay a web developer to build and maintain it for them...

Outsourcing
Post your project for outsourcing and get bids from qualified programmers, designers, interpreters, copywriters.


 

Code Walkthroughs

Datagrid Formatting the Data
We are able to format the content of the datagrid cell by one of two simple methods, dependant upon whether the column is a bound column or whether it is a template column. In our example we shall format the column to have to digits after the decimal point , followed by a...

Datagrid Highlight a Row With Click Through
It is relatively easy to add alternating colours to the rows in your datagrid. However, when we move the mouse over the rows we may want to highlight this row, and possibly to add the option of a click through based on the row selected...

Add a Delete Button to a Datagrid
To add a delete button to a datagrid follows a similar process to adding an edit button. In the datagrid header...

Add an Edit Button to a Datagrid
The datagrid has a predefined editColumn for handling the editing of a datagrid. Adding this simple column definition to a datagrid adds a powerful feature. When a row is not in edit mode the column item shows the word...

Making a Datagrid Row Editable
Two of the most popular methods of editing a datagrid in asp.net are to either select the row and take the user off to a different presentation of the data, or to change the formatting of the row presented in the database with appropriate edit text boxes, checkboxes and...

Adding Tooltips to Datagrid Rows
Adding tooltips to datagrid rows is easy, assuming that you have already created the code for adding row highlighting. In this article I shall assume that you have already read the article entitled Datagrid Highlight a Row With Click Through...

Binding a Datagrid to an Access Database
This list covers the full lifecycle of a content management system, from initially creating the content, through to delivering it to end users...

Adding Data to a DropDownList
The aim of this article is to answer the question 'How do I add items to a DropDownList?' Initially as part of the declaration for the DropDownList we can also define a number of items, much in the same way as in classic ASP...

Getting Current Date Time
In classic ASP we had now() which would return the current date and time. For asp.net this no longer exists. So what should we use...

Test if File Exists
Sometimes, in order to reduce our chance of error, when working with the filesystem in ASP.NET, we need to determine wether a file exists before performing an action on it. The following short piece of code will enable us to test whether a file exists...

Using Javascript with ASP.NET Form Elements
Adding simple pieces of Javascript to an Asp.net page can be acheived by adding to the attributes of the particular imagebutton or linkbutton. if its normal ASP.Net Button then you can...

Regular Expressions
In the table below we list the characters used in .Net regular expressions, together with their meaning, But first...

Authentication in Asp.net
Forms authentication in ASP.Net is far more easier and safe than Asp 3. It is possible to place a web.config file in any directory of a web site.Therefore, we are able to make most of a web site public, whilst providing authentication on, say, one directory...

Discussion Forums

General ASP.NET

.Net Programming

cSharp Home

Sql Server Home

Javascript / Client Side Development

IT Jobs

Ajax Programming

Ruby on Rails Development

Perl Programming

C Programming Language

C++ Programming

Python Programming Language

Laptop Suggestions?

TCL Scripting

Fortran Programming

Scheme Programming

15. Files

FAQ Home
   15.1 What is the best way to rename a file on the webserver in code?
   15.2 How to create a folder in ASP.NET?
   15.3 How to show the ASP.NET code to the users?
   15.4 How to read a html file in ASP.NET?
   15.5 How can I to get the path to the system area that holds temporary files?
   15.6 How to save a file in the client machine?
   15.7 How to get the physical path of a file?
   15.8 How to get the current filename?
   15.9 How to Upload files in ASP.NET?
   15.10 How to delete a file from the server?
   15.11 How to find the date and time the specified file or directory was last written to?
   15.12 How to get the File information using ASP.NET?
   15.13 How to create a .csv file that grabs the data from the database?
   15.14 How to read text file in ASP.NET?
   15.15 How to read specific characters from a text file?
   15.16 How to check files exist in a particular directory?
   15.17 What is a MemoryStream and how to use MemoryStream in ASP.NET?
   15.18 How to detect if the string indicating a file-system resource is a file or directory?



15.1 What is the best way to rename a file on the webserver in code?


Use namespace System.IO

VB.NET


File.Move("C:\Dir1\SomeFile.txt", "C:\Dir1\RenamedFileName.txt")


C#


File.Move(@"C:\Dir1\SomeFile.txt", @"C:\Dir1\RenamedFileName.txt")


Refer

Note: In a Web application, the code is running in the context of the machine\ASPNET account, which has limited privileges. If the error you are getting pertains to permissions, you might need to grant to the machine\ASPNET account the rights to create and delete files in the directory where you're working. Note that this could be a security issue.

 


15.2 How to create a folder in ASP.NET?


Use System.IO namespace
VB.NET


Dim path As String = ""
try
     ' Determine whether the directory exists.
     If Directory.Exists(path) Then
          Response.Write("That path exists already.")
          Return
     End If
     ' Try to create the directory.
     Dim di As DirectoryInfo = Directory.CreateDirectory(path)
     Response.Write(("Directory create successfully at " + Directory.GetCreationTime(path)))
catch ex as Exception
     Response.Write (ex.Message )
end try


C#


string path = @"c:\MyDir";
try
{
     // Determine whether the directory exists.
     if (Directory.Exists(path))
     {
          Response.Write ("That path exists already.");
          return;
     }
     // Try to create the directory.
     DirectoryInfo di = Directory.CreateDirectory(path);
     Response.Write("Directory create successfully at " + Directory.GetCreationTime(path));
}
catch(Exception ex)
{
     Response.Write (ex.Message );
}



15.3 How to show the ASP.NET code to the users?


Use namespace

  • System.IO
  • System.Text

VB.NET

 


Protected Function GetCode(filename As String) As String
     Dim sr As New StreamReader(filename)
     Dim sb As New StringBuilder()
     sb.Append("<code><pre>")
     sb.Append(sr.ReadToEnd())
     sb.Append("</pre></code>")
     sr.Close()
     Return sb.ToString()
     sb = Nothing
     sr = Nothing
End Function 'GetCode

Private Sub Button1_Click(sender As Object, e As System.EventArgs)
     Response.Write(GetCode((Server.MapPath("WebForm1.aspx") + ".vb")))
End Sub 'Button1_Click


C#


protected string GetCode(string filename)
{
     StreamReader sr =new StreamReader(filename );
     StringBuilder sb =new StringBuilder();
     sb.Append("<code><pre>");
     sb.Append(sr.ReadToEnd());
     sb.Append("</pre></code>");
     sr.Close();
     return sb.ToString();
     sb = null;
     sr = null;
}
private void Button1_Click(object sender, System.EventArgs e)
{
     Response.Write (GetCode(Server.MapPath ("WebForm1.aspx") + ".cs"));
}



15.4 How to read a html file in ASP.NET?


Use namespace System.IO
VB.NET


Dim file As String = Server.MapPath("temp.html")
Dim sr As StreamReader
Dim fi As New FileInfo(file)
Dim input As String = "<pre>"
If File.Exists(file) Then
sr = File.OpenText(file)
input += Server.HtmlEncode(sr.ReadToEnd())
sr.Close()
End If
input += "</pre>"
Me.Label1.Text = input


C#


string file = Server.MapPath ("temp.html");
StreamReader sr;
FileInfo fi = new FileInfo(file);
string input = "<pre>";
if(File.Exists(file))
{
     sr = File.OpenText(file);
     input += Server.HtmlEncode(sr.ReadToEnd());
     sr.Close();
}
input += "</pre>";
this.Label1.Text = input;



15.5 How can I to get the path to the system area that holds temporary files?


Use System.IO namespace
VB.NET


Dim filePath As String = Path.GetTempPath()
Dim fileName As String = Path.GetTempFileName()
Response.Write((filePath + "
"))
Response.Write(fileName)


C#


string filePath =Path.GetTempPath ();
string fileName = Path.GetTempFileName();
Response.Write (filePath + "
" );
Response.Write (fileName );



15.6 How to save a file in the client machine?


The browser will not allow you to save a file directly to a client machine. You could however do a Response.Redirect("http://server/filename"); which would send the file back to the browser, at which point the user would be prompted to save / open the file.


15.7 How to get the physical path of a file?


Use Request.Path


15.8 How to get the current filename?


VB.NET


Response.Write (Path.GetFileName(Request.PhysicalPath))


C#


Response.Write (Path.GetFileName(Request.PhysicalPath));



15.9 How to Upload files in ASP.NET?


Take a look at following articles

 


15.10 How to delete a file from the server?


VB.NET


System.IO.File.Delete(Server.MapPath("wnew.txt"))


C#


System.IO.File.Delete(Server.MapPath("wnew.txt"))


Make sure that you have permissions to delete a file.


15.11 How to find the date and time the specified file or directory was last written to?


Use namespace System.IO
VB.NET


dim path as string = Server.MapPath("page1.aspx")
Response.Write ( File.GetLastWriteTime(path))


C#


string path =Server.MapPath("page1.aspx");
Response.Write ( File.GetLastWriteTime(path));



15.12 How to get the File information using ASP.NET?


Use the namepsace System.IO
VB.NET


Dim fPath As String = Server.MapPath("orders.xml")
Dim fInfo As New FileInfo(fPath)
Dim strFileInfo As String
If fInfo.Exists Then
     strFileInfo = "Name: " + fInfo.Name + "<br />"
     strFileInfo += "Location: " + fInfo.FullName + "<br />"
     strFileInfo += "Created on: " + fInfo.CreationTime + "<br />"
     strFileInfo += "Extension: " + fInfo.Extension
Else
     strFileInfo = "The file <b>" + fPath + "</b> was not found."
End If
Response.Write(strFileInfo)


C#


string fPath = Server.MapPath("orders.xml");
FileInfo fInfo = new FileInfo(fPath);     
string strFileInfo ;
if(fInfo.Exists)
{
     strFileInfo = "Name: " + fInfo.Name + "<br />";
     strFileInfo += "Location: " + fInfo.FullName + "<br />";
     strFileInfo += "Created on: " + fInfo.CreationTime + "<br />";
     strFileInfo += "Extension: " + fInfo.Extension;
}
else
{
     strFileInfo = "The file <b>" + fPath + "</b> was not found.";
}     
Response.Write (strFileInfo);



15.13 How to create a .csv file that grabs the data from the database?



<asp:Button id="Button1" runat="server" Text="Button"></asp:Button>


VB.NET


Dim cn As SqlConnection
Dim cmd As SqlCommand
Dim filename As String
Dim dr As SqlDataReader
Dim i As Integer
Dim sb As System.Text.StringBuilder

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
     cn=NewSqlConnection("server=localhost;uid=sa;pwd=;database=northwind")
     filename = "products.csv"
     cmd = New SqlCommand("select * from products ", cn)
     cmd.Connection.Open()
     dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
     sb = New System.Text.StringBuilder

     'For field Names
     For i = 0 To dr.FieldCount - 1
          If i < (dr.FieldCount - 1) Then
          sb.Append(Chr(34) & dr.GetName(i) & _
               Chr(34) & ",")
          Else
          sb.Append(Chr(34) & dr.GetName(i) & _
               Chr(34) & vbCrLf)
          End If
     Next

     'For field Values
     While dr.Read()
          For i = 0 To dr.FieldCount - 1
          If i < (dr.FieldCount - 1) Then
               sb.Append(Chr(34) & _
                    dr.GetValue(i).ToString & Chr(34) & ",")
          Else
               sb.Append(Chr(34) & _
                    dr.GetValue(i).ToString & Chr(34) & vbCrLf)
          End If
          Next
     End While
     dr.Close()
     cn.Close()
     Response.ContentType = "Application/x-msexcel"
     Response.AddHeader _
          ("content-disposition", "attachment; filename=""" & _
               filename & """")
     'Write the file directly to the HTTP output stream.
     Response.Write(sb.ToString)
     Response.End()
End Sub


C#


SqlConnection cn ;
SqlCommand cmd ;
string filename ;