【问题标题】:Load file listed in listbox into rich text box将列表框中列出的文件加载到富文本框中
【发布时间】:2018-12-11 05:42:35
【问题描述】:

所以我正在创建一个程序,它在目录中显示文件,并且我正在尝试获取它,因此如果您单击其中的一个项目,它会将文件内容(以文本形式)加载到富文本框中。

numberedRTB1.RichTextBox.LoadFile(listBox1.SelectedItem.Name, RichTextBoxStreamType.RichText);

【问题讨论】:

  • 欢迎来到stackoverflow。请花一分钟时间回答tour,尤其是How to Ask,以及edit您的问题。
  • 如果你使用过DirectoryInfo().GetFiles(),那么你的listBox1.SelectedItem就是一个FileInfo类对象。您需要将项目转换为FileInfo 才能访问.Name 属性:(listBox1.SelectedItem as FileInfo).Name。您应该发布所有相关代码,这样就没有人猜测您正在使用什么对象。按照建议,使用tour

标签: c# winforms file-io


【解决方案1】:

如果您有文件的路径,您可以使用 File 类中的 ReadAllText(string path) 方法将文件的文本加载到 RichTextBox 中
小示例

richTextBox.Text = File.ReadAllText("path/to/file");

【讨论】:

    【解决方案2】:

    1) 你没有真正提出问题。

    2) 您很可能希望在列表中看到没有路径的名称,但需要完整路径来加载它们。

    对于其他列表,例如ListView,您可以使用项目的Tag,但ListBox 包含stringobject,两者都没有Tag 属性。

    所以请创建一个带有两个字符串字段和一个ToString 方法的class

    现在您看到了一个不错的名称,并且可以访问完整路径..


    类的示例代码:

    class ListItem
    {
        public string Name { get; set; }
        public string FullPath { get; set; }
    
        public ListItem(string filename, string fullpath )
        { Name = filename; FullPath = fullpath; }
    
        public ListItem(FileInfo fileinfo )
        { Name = fileinfo.Name; FullPath = fileinfo.FullName; }
    
    
        override public string ToString() { return Name; }
    }
    

    用于加载..:

    FileInfo fi = new FileInfo("D:\\test.rtf");
    // either..:
    listBox1.Items.Add(new ListItem(fi.Name, fi.FullName));
    // or :
    listBox1.Items.Add((new ListItem(fi));
    

    ..和访问:

    private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        ListItem item = listBox1.SelectedItem as ListItem;
        if (item != null)
        {
            if (File.Exists(item.FullPath) ) rtb.LoadFile(item.FullPath);
        }
    }
    

    【讨论】:

    • 很抱歉没有正确提出问题,我很少使用这个网站,除非我真的被卡住了(而且通常是因为愚蠢的原因)。不过谢谢你指出来。
    • 没问题。我猜对了您的问题吗?我的解决方案对您有用吗?
    猜你喜欢
    • 2012-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-29
    • 1970-01-01
    • 2019-11-13
    相关资源
    最近更新 更多