将DirectoryInfo内容加载到文本框中

时间:2012-01-09 18:43:50

标签: c# asp.net

我在遵循此Microsoft教程(步骤2)时遇到问题: Step 2: Fixing the Workflow for Unauthorized, Authenticated Users

我的ROOT中有完整的文件列表,因此当我在gridview中单击“编辑”时,文件的内容应显示在文本框中。 所以假设我单击EDIT到Default.aspx,然后应该显示Default.aspx中的内容/代码。

.ASPX:

 <asp:TextBox ID="FileContents" runat="server" Rows="10" TextMode="MultiLine" Width="95%"></asp:TextBox>

    <asp:GridView ID="FilesGrid" DataKeyNames="Name" runat="server" AutoGenerateColumns="False">
        <Columns>
            <asp:CommandField SelectText="View" ShowSelectButton="True" />
            <asp:CommandField ShowDeleteButton="True" />
            <asp:BoundField DataField="Name" HeaderText="Name" />
            <asp:BoundField DataField="Length" DataFormatString="{0:N0}" HeaderText="Size in Bytes"
                HtmlEncode="False" />
        </Columns>
    </asp:GridView>

.ASPX.CS:

protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            string appPath = Request.PhysicalApplicationPath;
            DirectoryInfo dirInfo = new DirectoryInfo(appPath);

            FileInfo[] files = dirInfo.GetFiles();

            FilesGrid.DataSource = files;
            FilesGrid.DataBind();
        }
    }

    protected void FilesGrid_SelectedIndexChanged(object sender, EventArgs e)
    {
        // Open the file and display it
        string fullFileName = FilesGrid.SelectedValue.ToString();
        string contents = File.ReadAllText(fullFileName);
        FileContents.Text = contents;
    }

2 个答案:

答案 0 :(得分:0)

可以更改此代码

    protected void FilesGrid_SelectedIndexChanged(object sender, EventArgs e)
    {
        // Open the file and display it
        string fullFileName = FilesGrid.SelectedValue.ToString();
        string contents = File.ReadAllText(fullFileName);
        FileContents.Text = contents;
    }

像这样阅读

    protected void FilesGrid_SelectedIndexChanged(object sender, EventArgs e)
    {
        // Open the file and display it
        string fullFileName = FilesGrid.SelectedValue.ToString();
        List<string> contents = new List<string>(File.ReadAllLines(fullFileName));
        FileContents.Text = contents.ToString();
    }

* 还要确保fullFileName具有完全限定的FilePath + FileName

答案 1 :(得分:0)

你的

<asp:GridView ID="FilesGrid" DataKeyNames="Name" runat="server" AutoGenerateColumns="False">

缺少onselectedindexchanged

<asp:GridView ID="FilesGrid" DataKeyNames="Name" runat="server" AutoGenerateColumns="False" OnSelectedIndexChanged="FilesGrid_SelectedIndexChanged">