首页 > 解决方案 > 任何文件夹的 C# 访问被拒绝

问题描述

当我选择任何文件夹时

文件夹对话框浏览器

我收到有关文件夹访问被拒绝的错误。这适用于所有文件夹、文档、我的计算机、桌面等,实际上是每个文件夹。我阅读了有关文件夹的用户访问权限(但磁盘上的每个文件夹?),并以管理员身份运行,但这对我没有帮助。如果我将程序发送给朋友,他们也会使用文件夹访问来选择路径吗?我已登录管理员帐户,我拥有所有权限,但我的程序没有。

/*
 * Created by SharpDevelop.
 * User: Tomek
 * Date: 2019-04-05
 * Time: 04:26
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Xml.Linq;

namespace meta_generator
{
    /// <summary>
    /// Description of MainForm.
    /// </summary>
    public partial class MainForm : Form
    {
        public MainForm()
        {
            //
            // The InitializeComponent() call is required for Windows Forms designer support.
            //
            InitializeComponent();

            //
            // TODO: Add constructor code after the InitializeComponent() call.
            //
        }

        OpenFileDialog files = new OpenFileDialog();
        FolderBrowserDialog metaOutput = new FolderBrowserDialog();

        string metapath;

        void Button1Click(object sender, EventArgs e)
        {
            files.Filter = "Wszystkie pliki (*.*)|*.*";
            files.Multiselect = true;

            if (files.ShowDialog() == DialogResult.OK)
            {
                foreach (String file in files.FileNames)
                {
                    textBox1.Text = textBox1.Text + ";" + file;
                }
            }
        }

        void Button2Click(object sender, EventArgs e)
        {
            metaOutput.Description = "Wybierz folder gdzie zostanie wygenerowany plik meta.xml";
            metaOutput.RootFolder = Environment.SpecialFolder.MyDocuments;

            if (metaOutput.ShowDialog() == DialogResult.OK)
            {
                metapath = metaOutput.SelectedPath;
                textBox2.Text = metapath;
            }
        }
        void Button3Click(object sender, EventArgs e)
        {
            if (textBox1.Text.Length > 0 && textBox2.Text.Length > 0)
            {
                XDocument meta = new XDocument(new XElement("meta"));

                foreach (String file in files.FileNames)
                {
                    XElement childFileTag = new XElement("file");
                    XAttribute sourcepath = new XAttribute("src", file);
                    childFileTag.Add(sourcepath);

                    meta.Root.Add(childFileTag);
                }

                if (checkBox1.Checked)
                    meta.Root.Add(new XElement("oop", "true"));

                meta.Save(metapath);
            }
        }


    }
}

标签: c#windowswinforms

解决方案


问题是你使用

meta.Save(metapath);

metapath文件夹(目录)名称(like c:\temp\,而不是文件名(like c:\temp\bob.xml)。

保存文件时,需要保存到完整的路径(包括文件名)。一个例子是:

meta.Save(Path.Combine(metapath, "bob.xml"));

或者,不要使用FolderBrowserDialog- 而是使用SaveFileDialog允许用户选择自己的文件名。


推荐阅读