I use this following code to remove the write protection folder so that I can delete that. But It won't work.
File.SetAttributes(#"F:\File", FileAttributes.Normal);
File.Delete(#"F:\File");
How can I remove the write protection?
If I can remove file protection from the disk, so give some codes to do that.
Any help will be appreciated
Thanks in advance
There is a difference between Folder and File. With this you will remove the readonly atribute and delete the folder.
var di = new DirectoryInfo(#"F:\File");
di.Attributes &= ~FileAttributes.ReadOnly;
di.Delete(true);
EDIT:
Formating USB drive. You can read the article.
public static bool FormatDrive(string driveLetter,
string fileSystem = "NTFS", bool quickFormat=true,
int clusterSize = 8192, string label = "", bool enableCompression = false )
{
if (driveLetter.Length != 2 || driveLetter[1] != ':'|| !char.IsLetter(driveLetter[0]))
return false;
//query and format given drive
ManagementObjectSearcher searcher = new ManagementObjectSearcher
(#"select * from Win32_Volume WHERE DriveLetter = '" + driveLetter + "'");
foreach (ManagementObject vi in searcher.Get())
{
vi.InvokeMethod("Format", new object[]
{ fileSystem, quickFormat,clusterSize, label, enableCompression });
}
return true;
}
You should put the driveLetter like this: "F:"
Related
This question already has answers here:
How do I determine a mapped drive's actual path?
(14 answers)
Closed 2 years ago.
I have ran into an issue where by when the user adds a file directory to my project the link is stored as their own mapped drive. For example;
C:\Location\Location
However, some users may have the C: drive on the server mapped as M: for example. Thus are unable to locate the file.
What I would like to do is replace this with the actual server name, ie
\\ArtServer\
I know that I could achieve this by replacing the opening part of the string, however if more servers are added in the future then this will obviously fallover in a huge mess. Currently the user grabs the file path using a standard get file dialogue;
public static string GetFilePath(string filter = "All Files (*.*)|*.*", string initialDirectory = #"This PC")
{
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Filter = filter;
fileDialog.FilterIndex = 1;
fileDialog.Multiselect = false;
fileDialog.InitialDirectory = Directory.Exists(initialDirectory) ? initialDirectory : #"This PC";
if (fileDialog.ShowDialog() == true)
{
return fileDialog.FileName;
}
else
{
return null;
}
}
Is there anyway I can achieve this with what I currently have?
Thank you to #ADyson for all of your help. I decided to use an answer provided by ibram from the thread linked above. For anyone else who has the same issue I have posted what I had done;
public static string GetUNCPath(string path)
{
if (path.StartsWith(#"\\"))
{
return path;
}
ManagementObject mo = new ManagementObject();
mo.Path = new ManagementPath(String.Format("Win32_LogicalDisk='{0}'", path));
// DriveType 4 = Network Drive
if (Convert.ToUInt32(mo["DriveType"]) == 4)
{
return Convert.ToString(mo["ProviderName"]);
}
else
{
return path;
}
}
public static string GetFilePath(string filter = "All Files (*.*)|*.*", string initialDirectory = #"This PC")
{
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Filter = filter;
fileDialog.FilterIndex = 1;
fileDialog.Multiselect = false;
fileDialog.InitialDirectory = Directory.Exists(initialDirectory) ? initialDirectory : #"This PC";
if (fileDialog.ShowDialog() == true)
{
// Split the file directory to gain root path
// Use GetUNCPath to convert root path to server name
string s = fileDialog.FileName;
int index = s.IndexOf(':') + 1;
string rootPath = GetUNCPath(s.Substring(0, index));
string directory = s.Substring(index);
return rootPath + directory;
}
else
{
return null;
}
}
I am not a C# programer but I need to format drive with 32KB cluster using C#. I found "Format method of the Win32_Volume class" but when I am trying to format drive I always get an error 15 (Cluster size is too small). This is my code:
public static int DriveFormatting(string driveLetter)
{
string FileSystem = "FAT32", Label = "";
Boolean QuickFormat = true, EnableCompression = false;
UInt32 ClusterSize = 32;
int result = -1;
ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_Volume WHERE DriveLetter = '"+ driveLetter +"'");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
foreach(ManagementObject management in searcher.Get())
{
Console.WriteLine("Formating disk " + driveLetter + "...");
result = Convert.ToInt32(management.InvokeMethod("Format", new object[] { FileSystem, QuickFormat, ClusterSize, Label, EnableCompression }));
}
return result;
}
How can I do this? Thanks in advance.
I'm trying to copy files over from the desktop to a USB drive programmatically. However, when trying to run this code, I am geting an error stating that part of the path could not be found:
if (dr == DialogResult.Yes)
{
string selected = comboBox1.GetItemText(comboBox1.SelectedItem);
string filePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string filefolder = #"\UpgradeFiles";
string fileLocation = filePath + filefolder;
if (!Directory.Exists(fileLocation))
{
Directory.CreateDirectory(fileLocation);
}
else if (Directory.Exists(fileLocation))
{
DirectoryInfo di = new DirectoryInfo(fileLocation);
FileInfo[] fileList = di.GetFiles();
foreach (FileInfo file in fileList)
{
string DrivePath = Environment.GetFolderPath(
Environment.SpecialFolder.MyComputer);
string CopyToDrive = comboBox1.Text;
file.CopyTo(DrivePath + CopyToDrive, false);
}
}
}
The combobox contains the selected drive letter. Am I approaching this wrong when trying to add "computer\driveletter"?
Your File.CopyTo(DrivePath + CopyToDrive, false) should be:
File.CopyTo(CopyToDrive + File.Name, false);
but with a bit of syntactic sugar like using Path.Combine or String.Format instead of just "+".
The issue is that File.CopyTo requires both the directory AND filename of the end location, when you're just providing the directory. This can be seen in the documentation for the method call here: https://msdn.microsoft.com/en-us/library/f0e105zt(v=vs.110).aspx
I'm writing a program that needs to get the install date and version information of all the programs in a registry. I am able to get a list of all of the programs, but I do not know how to access any information about the programs themselves. If I was able to determine the filepath to where the files are located I would be able to access this information. I happen to know that the programs I'm interested in are all located in the C:\\Program Files (x86)\ folder, but they are in subfolders within this that I am unable to specify. Any ideas on how to get the filepaths of the files I am retrieving?
Here's my code:
public List<BSAApp> getInstalledApps( string computerName )
{
List<BSAApp> appList = new List<BSAApp>();
ManagementScope ms = new ManagementScope();
ms.Path.Server = computerName;
ms.Path.NamespacePath = "root\\cimv2";
ms.Options.EnablePrivileges = true;
ms.Connect();
ManagementClass mc = new ManagementClass( "StdRegProv" );
mc.Scope = ms;
ManagementBaseObject mbo;
mbo = mc.GetMethodParameters( "EnumKey" );
mbo.SetPropertyValue( "sSubKeyName", "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths" );
string[] subkeys = (string[])mc.InvokeMethod( "EnumKey", mbo, null ).Properties["sNames"].Value;
if( subkeys != null )
{
foreach( string strKey in subkeys )
{
string path = ?????
FileVersionInfo info = FileVersionInfo.GetVersionInfo( path );
appList.Add( new BSAApp( strKey, info.ProductVersion ) );
}
}
return appList;
}
ManagementObjectSearcher mos = new ManagementObjectSearcher("SELECT * FROM Win32_Product");
foreach(ManagementObject mo in mos.Get())
{
Console.WriteLine(mo["Name"]);
Console.WriteLine(mo["InstallState"]);
}
Get installed applications in a system
But as mentioned in that thread, it has its own drawbacks.
I have used the ImDisk library with the .NET wrapper to create a Virtual Disk in my C# application. However, after I create the device, I apparently need to create a Mount Point as well for the device to actually show as a Drive Letter. I don't completely understand what is supposed to be supplied for it to create a Mount Point, but I believe this pertains more to Virtual devices than the library.
My Function:
public bool CreateRAMDisk()
{
// Create Empty RAM Disk
char driveLetter = ImDiskAPI.FindFreeDriveLetter();
ImDiskAPI.CreateDevice(52428800, 0, 0, 0, 0, ImDiskFlags.DeviceTypeHD | ImDiskFlags.TypeVM, null, false, driveLetter.ToString(), ref deviceID, IntPtr.Zero);
string mountPoint = driveLetter + #":\Device\ImDisk0";
ImDiskAPI.CreateMountPoint(mountPoint, deviceID);
// Format the Drive for NTFS
if (FormatDrive(driveLetter.ToString(), "NTFS", true, 4096, "", false))
{
CreateMountPoint Definition:
public static void CreateMountPoint(string Directory, uint DeviceNumber);
//
// Summary:
// Creates a mount point for an ImDisk virtual disk on an empty subdirectory
// on an NTFS volume.
//
// Parameters:
// Directory:
// Path to an empty subdirectory on an NTFS volume
//
// DeviceNumber:
// Device number of an existing ImDisk virtual disk
UPDATE
FormatDrive Function:
public static bool FormatDrive(string driveLetter, string fileSystem, bool quickFormat, int clusterSize, string label, bool enableCompression)
{
driveLetter = driveLetter + ":";
if (driveLetter.Length != 2 || driveLetter[1] != ':'|| !char.IsLetter(driveLetter[0]))
{
return false;
}
//query and format given drive
ManagementObjectSearcher searcher = new ManagementObjectSearcher(#"select * from Win32_Volume WHERE DriveLetter = '" + driveLetter + "'");
foreach (ManagementObject vi in searcher.Get())
{
vi.InvokeMethod( "Format", new object[] {fileSystem, quickFormat, clusterSize, label, enableCompression} );
}
return true;
}
Turns out their were some issues with the parameters being passed in CreateDevice(), which was allowing it to not generate errors but not fully completing the setup process.
Thanks for the help!
you must add ":" at the end of driveLetter parameter