未知昵称
2018-06-07 07:56
采纳率: 89.7%
浏览 2.2k

C# treeview,以及路径获取

图片说明

如图所示treeview新建了几个节点,节点名称如图所示,
现在创建节点双击事件。双击节点,在当前目录的一个叫record的文件下创建和该节点相通名字的txt文件,代码如下所示,

string str = e.Node.Text;

string path1 = @"record";

FileStream fs = new FileStream(path1+"/"+str+".txt",FileMode.Create,FileAccess.Write);

StreamWriter sw = new StreamWriter(fs);

fs.Close();

button事件去读取写入txt文档,
如果我再要去读取刚刚创建的txt文档,往里面写入内容

string path = ?? //获取这个名字的txt文档的路径该怎么写?

StreamWriter sw = new StreamWriter(path, true);

sw.WriteLine(“testcontent”);

sw.Close();

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • 笨鸟后飞唯勤补拙 2018-06-07 09:35
    已采纳
     TreeNode select_node;
            private void treeView1_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
            {
                //treeView1.SelectedNode.Level 获取节点的深度,比如节点11的深度为2
                //treeView1.SelectedNode.Index 获取节点在当前集合的索引,比如节点11在节点1的第0个位置
                select_node = treeView1.SelectedNode;
                string str = e.Node.Text;
                string path1 = @"record";
                FileStream fs = new FileStream(path1 + "/" + str + ".txt", FileMode.Create, FileAccess.Write);
                fs.Close();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                string path1 = @"record";
                FileStream fs = new FileStream(path1 + "/" + select_node.Text + ".txt", FileMode.Create, FileAccess.Write);
                StreamWriter sw = new StreamWriter(fs);
                sw.Write(textBox1.Text);
                sw.Flush();
                fs.Close();
            }
    

    图片说明

    答案够详细了吧,给分给分啦。

    你要做个复杂点文件目录的话,就可以用到treeView1.SelectedNode.Level和treeView1.SelectedNode.Index

    点赞 打赏 评论
  • sun44__ 2018-06-07 08:58

    可以判断一下,如果存在Node1.txt,读它,写数据进去,这样写6个if就可以了,目前就想到这个办法,有点麻烦,

    点赞 打赏 评论
  • 笨鸟后飞唯勤补拙 2018-06-07 09:29

    具体代码
    ```TreeNode select_node;
    private void treeView1_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
    {
    //treeView1.SelectedNode.Level 获取节点的深度,比如节点11的深度为2
    //treeView1.SelectedNode.Index 获取节点在当前集合的索引,比如节点11在节点1的第0个位置
    select_node = treeView1.SelectedNode;
    string str = e.Node.Text;
    string path1 = @"record";
    FileStream fs = new FileStream(path1 + "/" + str + ".txt", FileMode.Create, FileAccess.Write);
    fs.Close();
    }

        private void button1_Click(object sender, EventArgs e)
        {
            string path1 = @"record";
            FileStream fs = new FileStream(path1 + "/" + select_node.Text + ".txt", FileMode.Create, FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs);
            sw.Write(textBox1.Text);
            sw.Flush();
            fs.Close();
        }
    
    实际截图![图片说明](https://img-ask.csdn.net/upload/201806/07/1528363774_766363.png)
    
    点赞 打赏 评论

相关推荐 更多相似问题