• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1495
  • Last Modified:

Change file attribute with c# cmd command

I want to change file attribute with cmd.exe via c#.
But when I Executed the program. It don't any changes.

Please help, where's my mistake?

string arguments = @"attrib -r -h -s C:\WINDOWS\system32\drivers\etc\hosts";
System.Diagnostics.Process.Start("cmd.exe", arguments);

Open in new window

0
fancyfanta
Asked:
fancyfanta
  • 3
  • 3
3 Solutions
 
jasonduanCommented:
Do you really have to use "cmd.exe"?

the following C# code will have the same effect without launching a seperate process.
FileInfo f =  new FileInfo(@"C:\WINDOWS\system32\drivers\etc\hosts");
f.Attributes = f.Attributes & ~FileAttributes.ReadOnly & ~FileAttributes.System & ~FileAttributes.Hidden;


File.SetAttributes(...) can also be used to set file attributes if you know the exact desired attributes.
0
 
fancyfantaAuthor Commented:
Thank you @jasonduan,
and then how can I lock down the file? I mean I want to get back the ex attributes.
Thanks
0
 
jasonduanCommented:
you can save the attributes:
FileAttributes orgAttributes = f.Attributes;
then restore it when you done:
f.Attributes = orgAttributes;
or
File.SetAttributes(@"c:\....", orgAttributes);
0
Cloud Class® Course: CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

 
fancyfantaAuthor Commented:
It gives error:
The name 'orgAttributes' does not exist in the current context
0
 
fancyfantaAuthor Commented:
Sorry my mistake.
But I want to change attributes to readonly, system file and hidden
How can i?
I dont want to orginals
0
 
Russell_VenableCommented:
This is one of the best examples on the net that I
You can refer too. http://www.csharp-examples.net/file-attributes/
0
 
jasonduanCommented:
this code changes attributes to readonly, system file and hidden

File.SetAttributes(@"c:\....", FileAttributes.ReadOnly | FileAttributes.System | FileAttributes.Hidden);
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 3
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now