• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1430
  • 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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
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

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone 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