ASP.NET Tutorial/File Directory/File — различия между версиями

Материал из .Net Framework эксперт
Перейти к: навигация, поиск
м (1 версия)
 
м (1 версия)
 
(нет различий)

Текущая версия на 11:57, 26 мая 2010

Creating a File (C#)

<%@ Page Language="c#" %>
<%@ Import Namespace = "System.IO" %>
<script language="c#" runat="Server">
  public void CreateFile(object sender, EventArgs e)
  {
    StreamWriter myFileStream = null;
        if(TextContent.Text.Trim().Length > 0)
        {
      try
      {
        myFileStream = File.CreateText(Server.MapPath(".\\Upload\\") + "test.txt");
        myFileStream.WriteLine(TextContent.Text);
        myFileStream.Close();
        Output.Text = "File Successfully Created!";
      }
      catch (Exception exc)
      {
        Output.Text = "Error in Creating file. Error is " + exc.ToString();
      }
      finally
      {
        if(myFileStream != null)
          myFileStream.Close();
      }
    }
    else
    {
      Output.Text = "File not created, because you didn"t enter anything!";
    }
  }
</script>
<HTML>
  <HEAD>
    <title>Creating a File</title>
  </HEAD>
  <body>
    <form id="Form1" method="post" runat="server">
      <asp:Label ID="Msg" Runat="server" Text="Please enter some text: "></asp:Label><br>
      <asp:TextBox ID="TextContent" Runat="server" TextMode="MultiLine" Rows="10" Columns="75"></asp:TextBox><br>
      <asp:Button ID="Submit" Runat="server" Text="Submit" OnClick="CreateFile"></asp:Button>
      <asp:Label ID="Output" Runat="server"></asp:Label>
    </form>
  </body>
</HTML>


Creating a File (VB)

<%@ Page Language="vb" Explicit="true" Strict="true" %>
<%@ Import Namespace = "System.IO" %>
<script language="vb" runat="Server">
    Sub CreateFile(sender As Object, e As EventArgs)
        If Trim(TextContent.Text).Length > 0 Then
            Dim myFileStream As StreamWriter = Nothing
            Try
                myFileStream = File.CreateText(Server.MapPath(".\Upload\") & "test.txt")
                myFileStream.WriteLine(TextContent.Text)
                myFileStream.Close()
                Output.Text = "File Successfully Created!"
            Catch exc As Exception
                Output.Text = "Error in Creating file. Error is " & exc.ToString()
            Finally
        If Not myFileStream Is Nothing Then
          myFileStream.Close()
        End If
            End Try
        Else
            Output.Text = "File not created, because you didn"t enter anything!"
        End If
    End Sub
</script>
<HTML>
  <HEAD>
    <title>Creating a File</title>
  </HEAD>
  <body>
    <form id="Form1" method="post" runat="server">
      <asp:Label ID="Msg" Runat="server" Text="Please enter some text: "></asp:Label><br>
      <asp:TextBox ID="TextContent" Runat="server" TextMode="MultiLine" Rows="10" Columns="75"></asp:TextBox><br>
      <asp:Button ID="Submit" Runat="server" Text="Submit" OnClick="CreateFile"></asp:Button>
      <asp:Label ID="Output" Runat="server"></asp:Label>
    </form>
  </body>
</HTML>


Delete a file (C#)

<%@ Import Namespace="System" %>
<%@ Import Namespace="System.IO" %>
<%@ Page Language="C#" %>
<script runat="server">
    void Page_Load(Object Source, EventArgs E)
    {
        MessageLiteral.Text = "";
    }
    
    void DeleteFile(Object Source, EventArgs E)
    {
        FileInfo fileSource = new FileInfo(FileNameTextBox.Text);
    
      try{
          if (fileSource.Exists){
              fileSource.Delete();
              MessageLiteral.Text = "File has been deleted.";
        }
          else
              MessageLiteral.Text = FileNameTextBox.Text + " does not exist.";
      }
      catch (Exception _Error){
        MessageLiteral.Text = _Error.Message;
      }
    }
</script>
<html>
  <head>
    <title>Deleting a File</title>
  </head>
  <body>
    <form runat="server">
      <h4>Type Path/Name of file to delete it (disabled for live demo)
      </h4>
      
        <asp:TextBox id="FileNameTextBox" runat="server"></asp:TextBox>
        &nbsp;<asp:Button id="DeleteFileButton" onclick="DeleteFile" runat="server" Text="Delete File"></asp:Button>
      
      
        <asp:Literal id="MessageLiteral" runat="server"></asp:Literal>
      
    </form>
  </body>
</html>


Delete a file (VB)

<%@ Import Namespace="System" %>
<%@ Import Namespace="System.IO" %>
<%@ Page Language="VB" %>
<script runat="server">
    Public Sub Page_Load(Source As Object, E As EventArgs)
        MessageLiteral.Text = ""
    End Sub
    
    Public Sub DeleteFile(Source As Object, E As EventArgs)
       "Delete the file if it exists 
    Try
          If File.Exists(FileNameTextBox.Text) Then
              File.Delete(FileNameTextBox.Text) 
              MessageLiteral.Text = "File has been deleted."
          Else
              MessageLiteral.Text = FileNameTextBox.Text & " does not exist."
          End If
    Catch _Error As Exception
      MessageLiteral.Text = _Error.Message
    End Try
    
    End Sub
</script>
<html>
  <head>
    <title>Deleting a File</title>
  </head>
  <body>
    <form runat="server">
      <h4>Type Path/Name of file to delete it (disabled for live demo)
      </h4>
      
        <asp:TextBox id="FileNameTextBox" runat="server"/>
        &nbsp;<asp:Button id="DeleteFileButton" onclick="DeleteFile" runat="server" Text="Delete File"></asp:Button>
      
      
        <asp:Literal id="MessageLiteral" runat="server"></asp:Literal>
      
    </form>
  </body>
</html>


Get file information (VB.net)

<%@ Import Namespace="System.IO" %>
<script language="VB" runat="server">
   
   sub Page_Load(Sender as Object, e as EventArgs)
      dim f as new FileInfo(Server.MapPath("test.aspx"))
      lblMessage.Text = "File information<br>" & _
         "<b>Name: </b>" & f.Name & "<br>" & _
         "<b>Path: </b>" & f.DirectoryName & "<br>" & _
         "<b>Last access time: </b>" & f.LastAccessTime & _
            "<br>" & _
         "<b>Last write time: </b>" & f.LastWriteTime & _
            "<br>" & _
         "<b>Length: </b>" & f.Length & " bytes"
   end sub
</script>
<html><body>
   <asp:label id="lblMessage" runat=server/>
</body></html>


Load file content to DropDownList (C#)

<%@ Page Language="C#" Debug="true" %>
<script runat="server">
private void Page_Load(object sender, System.EventArgs e) {
  string MyFileName;
  System.IO.StreamReader ObjectStreamReader = null;
  ArrayList FileLines = new ArrayList();
  MyFileName = Page.MapPath("Data.txt");
  try {
    ObjectStreamReader = new System.IO.StreamReader (MyFileName);
    while (ObjectStreamReader.Peek() > -1) {
      FileLines.Add(ObjectStreamReader.ReadLine());
    }
    FileLines.Sort();
    Label1.Text = "Select a title:";    
    DropDownList1.DataSource = FileLines;
    DropDownList1.DataBind(); 
  } catch (Exception ObjectError) {
    Label1.Text = ObjectError.Message;
    DropDownList1.Visible = false;
  } finally {
    if (ObjectStreamReader != null) {
                  ObjectStreamReader.Close();
    }
  }
      
}
</script>
<html>
  <head>
  </head>
  <body>
    <form runat="server">
      <asp:Label id="Label1" runat="server"></asp:Label>
      <asp:DropDownList id="DropDownList1" runat="server"></asp:DropDownList>
    </form>
  </body>
</html>


Load file content to DropDownList (VB)

<%@ Page Language="VB" Debug="true" %>
<script runat="server">
Sub Page_Load (Sender As Object, E As EventArgs)
  Dim MyFileName as String
  Dim ObjectStreamReader as System.IO.StreamReader
  Dim FileLines as New ArrayList()
  MyFileName = Page.MapPath("Data.txt")
  Try
    ObjectStreamReader = new System.IO.StreamReader (MyFileName)
    While ObjectStreamReader.Peek() > -1
      FileLines.Add(ObjectStreamReader.ReadLine())
    End While
    FileLines.Sort()
    Label1.Text = "Select a title:"    
    DropDownList1.DataSource = FileLines
    DropDownList1.DataBind() 
  Catch ObjectError as Exception
      Label1.Text = ObjectError.Message
      DropDownList1.Visible = False
  Finally
    If Not ObjectStreamReader Is nothing Then
                  ObjectStreamReader.Close()
    End If
  End Try
End Sub
</script>
<html>
  <head>
  </head>
  <body>
    <form runat="server">
      <asp:Label id="Label1" runat="server"></asp:Label>
      <asp:DropDownList id="DropDownList1" runat="server"></asp:DropDownList>
    </form>
  </body>
</html>


Opening a File (C#)

<%@ Page Language="c#" Explicit="true" Strict="true" %>
<%@ Import Namespace = "System.IO" %>
<script language="c#" runat="Server">
  public void ReadFile(object sender, EventArgs e)
  {
    StreamReader FileStreamReader = null;
    try
    {
      FileStreamReader = File.OpenText (Server.MapPath(".\\Upload\\") + "test.txt");
      TextContent.Text = FileStreamReader.ReadToEnd();
      FileStreamReader.Close();
      OutputLabel.Text = "File Succesfully Read!";
    }
    catch (Exception exc)
    {
      OutputLabel.Text = "Error in Reading file. Error is " + exc.ToString();
    }
    finally
    {
      if(FileStreamReader!=null)
        FileStreamReader.Close();
    }
  }
</script>
<html>
  <head>
    <title>Opening a File</title>
  </head>
  <body>
    <form id="Form1" method="post" runat="server">
      <asp:TextBox ID="TextContent" Runat="server" TextMode="MultiLine" Rows="10" Columns="75"></asp:TextBox><br>
      <asp:Button ID="Submit" Runat="server" Text="Submit" OnClick="ReadFile"></asp:Button>
      <asp:Label ID="OutputLabel" Runat="server"></asp:Label>
    </form>
  </body>
</html>


Opening a File (VB)

<%@ Page Language="vb" Explicit="true" Strict="true" %>
<%@ Import Namespace = "System.IO" %>
<script language="vb" runat="Server">
Sub ReadFile(ByVal sender As Object, ByVal e As EventArgs)
  Dim FileStreamReader As StreamReader
  Try
    FileStreamReader = File.OpenText(Server.MapPath(".\Upload\") & "test.txt")
    TextContent.Text = FileStreamReader.ReadToEnd()
    FileStreamReader.Close()
    OutputLabel.Text = "File Succesfully Read!"
  Catch exc As Exception
    OutputLabel.Text = "Error in Reading file. Error is " & exc.ToString()
  Finally
    If Not FileStreamReader Is Nothing Then
      FileStreamReader.Close()
    End If
  End Try
End Sub    
</script>
<html>
  <head>
    <title>Opening a File</title>
  </head>
  <body>
    <form id="Form1" method="post" runat="server">
      <asp:TextBox ID="TextContent" Runat="server" TextMode="MultiLine" Rows="10" Columns="75"></asp:TextBox><br>
      <asp:Button ID="Submit" Runat="server" Text="Submit" OnClick="ReadFile"></asp:Button>
      <asp:Label ID="OutputLabel" Runat="server"></asp:Label>
    </form>
  </body>
</html>


Rename File

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Rename" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Rename File</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h1>Rename File</h1>
        <asp:Label ID="lblOldName" runat="server" Text="Old Name: "></asp:Label>
        <asp:TextBox ID="txtOldName" runat="server"></asp:TextBox>
        <br />
        <asp:Label ID="lblNewName" runat="server" Text="New Name: "></asp:Label>
        <asp:TextBox ID="txtNewName" runat="server"></asp:TextBox><br />
        <br />
        <asp:Button ID="btnBadRename" runat="server" OnClick="btnBadRename_Click" Text="Bad Rename" />
        <asp:Button ID="btnGoodRename" runat="server" OnClick="btnGoodRename_Click" Text="Good Rename" /></div>
    </form>
</body>
</html>
File: Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.IO;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class Rename : System.Web.UI.Page
{
    protected void btnBadRename_Click(object sender, EventArgs e)
    {
        string appPath = Request.PhysicalApplicationPath;
        string oldPath = Path.rubine(appPath, txtOldName.Text);
        string newPath = Path.rubine(appPath, txtNewName.Text);
        File.Move(oldPath, newPath);
    }
    protected void btnGoodRename_Click(object sender, EventArgs e)
    {
        string oldPath = Server.MapPath(txtOldName.Text);
        string newPath = Server.MapPath(txtNewName.Text);
        File.Move(oldPath, newPath);
    }
}