Tarida George
Tarida George

Reputation: 1303

C# properties FileSystem

 DirectoryInfo directory;
 public string Name {
            get { return this.directory.Name; }
            set { this.directory.Name = value; }
        }

Hi. I have this code in c# . It doesn't work I get this error:

Property or Indexer System.Io.FileSystemInfo.Name cannot be assigned to -- it's read only.

What can I do ?

Upvotes: 0

Views: 200

Answers (3)

nickolayratchev
nickolayratchev

Reputation: 1206

DirectoryInfo.Name is read-only, you cannot modify it. You should remove it from your code. However, if you'd like to change a directory's name, you would write something like this:

System.IO.Directory.Move("oldDirName", "newDirName");

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500525

I can think of three possibilities:

  • Remove the setter entirely, making it a read-only property
  • Change the value of directory to refer to the specified directory
  • (Bizarre and dangerous!) Rename the directory on the file system so that its name is now as specified

Without knowing what your property is really meant to represent, it's hard to really say which of these options is appropriate, if any.

Upvotes: 1

cdhowie
cdhowie

Reputation: 169018

Just as the compiler says, DirectoryInfo's inherited Name property is read-only. The expression this.directory.Name = value; is erroneous; you cannot assign to a read-only property.

To make your class' Name property read-only, just remove the setter altogether. If you want the property to be writable, then you need to figure out what it means to write to your Name property and carry out whatever logic is necessary to transform the object's state appropriately.

Upvotes: 1

Related Questions