开发者

Writing to a subfolder in c#

开发者 https://www.devze.com 2023-04-02 16:21 出处:网络
I\'m having a little bit of trouble writing to a text file within a folder I tried to create. It said I didn\'t have开发者_StackOverflow中文版 access to the path \'C:\\\'

I'm having a little bit of trouble writing to a text file within a folder I tried to create. It said I didn't have开发者_StackOverflow中文版 access to the path 'C:\'

Could anyone tell me why and how to fix it? Thanks!

string file_name = Environment.CurrentDirectory;
    file_name += @"\.";
    file_name = (string)combobox1.SelectedValue;
    file_name += @"\.";
    file_name += (string)combobox2.SelectedValue;
    TextWriter name = new StreamWriter(file_name);

EDIT: Here's the new code after revisions...

var location = Path.Combine(Environment.CurrentDirectory, (string)combobox1.SelectedItem);
Directory.CreateDirectory(location);
var path = Path.Combine(location, combobox2.SelectedItem);
TextWriter name = new StreamWriter(path, true);

My goal is to write a text file to \\.txt

Could anyone tell me how? Thanks!


have you checked the value of file_name to make sure is a valid Path?

you have missed a concatenation anyway at line number 3

string file_name = Environment.CurrentDirectory;
    file_name += @"\.";
    file_name += (string)combobox1.SelectedValue;  // <--
    file_name += @"\.";
    file_name += (string)combobox2.SelectedValue;
    TextWriter name = new StreamWriter(file_name);


The account that the application is running under does not have write permissions in the location you are trying to save the file to.

This article goes over how to resolve this issue:

http://www.phdcc.com/findinsite/instperm.htm


You should be using Path.Combine():

var fileName = Path.Combine(Environment.CurrentDirectory, (string)comboBox1.SelectedValue,
                            (string)comboBox2.SelectedValue);

If at that point it still doesn't work, at least you'll know it's actually a permissions/existence/etc. issue, rather than an issue with the way you've constructed the file name.


The solution here is a combination of what everyone else has said.

As has already been pointed out, this line:

file_name = (string)combobox1.SelectedValue;

is incorrectly doing an assignment (=) instead of a concatenation (+=). This means that if comboxbo1.SelectedValue is null, your path becomes \., which is the root directory of the drive.

You need to remember that it's legal for SelectedValue to be null, because a combo box can have an empty selection. You need to handle that case, perhaps by disabling your save functionality until the combo boxes have valid selections.

This isn't really a problem with permissions; it's unlikely that you actually need or intend to write to the root directory, which is why you aren't given that permission in the first place.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号