For installation using .NET, I wish to give write permission to a particular file in the folder using cacls.exe, so I have referred How to give Read/Write permissions to a Folder during installation using .NET and I have used the code from Setting File or Directory permissions ACE entries with .NET using CACLS.EXE.
After installation, on form load, I could read the file file.txt which is located at C:\Program Files\MyCompany\MyProduct , with below code:
private void Form1_Load(object sender, EventArgs e)
{
//Some code
DirectoryPermission dp = new
DirectoryPermission(filename, "Everyone", "F");
dp.SetAce();
foffset = read_file();
}
string filename = "file.txt";
private double read_file()
{
double value = 0;
try
{
value = Double.Parse(System.IO.File.ReadAllText(#filename));
return value;
}
catch
{
System.IO.File.WriteAllText(#filename, value.ToString());
return 0;
}
}
But on a button click I couldn't write the file with new value, so I wrote the below code and did installation, still the problem persist:
private void button1_Click(object sender, EventArgs e)
{
try{
DirectoryPermission dp = new
DirectoryPermission(filename , "Everyone", "F");
dp.SetAce();
System.IO.File.WriteAllText(#filename , offset.ToString());
}
catch
{}
}
I'm giving full control to all the users, but I'm not able to write the file. and I'm getting this error
Exception thrown: 'System.UnauthorizedAccessException' in mscorlib.dll
Please help me in this.
Related
There is nothing wrong in the syntax of my code but whenever I try to run it keeps saying "The process cannot access the file because it is being used by another process". The only way I am running my application is my ending my application from the task manager. Please help me by explaining why this is happening and how to fix it.
private void btnLogin_Click(object sender, EventArgs e)
{
if (File.Exists("users.txt"))
{
string[] users = File.ReadAllLines("users.txt");
bool userFound = false;
foreach (string user in users)
{
string[] splitDetails = user.Split('~');
string username = splitDetails[1];
string password = splitDetails[2];
if ((txtBoxUsername.Text == username) && (txtBoxPassword.Text == password))
{
userFound = true;
break;
}
}
if (userFound)
{
Hide();
HomeForm home = new HomeForm();
home.Show();
}
else
{
MessageBox.Show("User details are incorrect",
"Incorrect details entered");
}
}
else
{
MessageBox.Show("No users have been registered", "No users");
}
}
private void btnRegister_Click(object sender, EventArgs e)
{
Hide();
RegisterForm registerForm = new RegisterForm();
registerForm.Show();
}
This application is for my a level software systems development coursework and I am coding it in c#. I have only been learning c# for the past 5 months so I am still a beginner. I have already tried to find the answer to my problem in stack overflow and other websites.
I am expecting my application to launch when I press run, but instead I get a dialog box saying:
Error Unable to copy file "obj\Debug\SSD AS2 coursework.exe" to "bin\Debug\SSD AS2 coursework.exe". The process cannot access the file 'bin\Debug\SSD AS2 coursework.exe' because it is being used by another process.
SSD AS2 coursework
Check if you are closing all windows of your application when finalizing the app.
You must use Application.Exit() in any events that are going to finalize your application.
You can read more on the Documentation
It seems like the file you are trying to open is being used by another process try to close your text editor or another program writing to that file.
it is still possible to overcome the issue by using FileShare.ReadWrite and use the file from multiple processes, example on the following code:
FileStream fileStream = new FileStream("c:\users.txt", FileMode.Open,
FileAccess.Read, FileShare.ReadWrite);
StreamReader fileReader = new StreamReader(fileStream);
while (!fileReader.EndOfStream)
{
string user = fileReader.ReadLine();
string[] splitDetails = user.Split('~');
// the rest of the user logic in here...
}
fileReader.Close();
fileStream.Close();
I'm trying to get the items from within a folder on an Android phone.
However the FolderBrowserDialog won't let me select a folder from within in the phone. The path looks like this This PC\Xperia Z3 Compact\SD Card\Music
To select a folder I'm currently using:
private void button_Click(object sender, EventArgs e)
{
System.Windows.Forms.FolderBrowserDialog dlg = new System.Windows.Forms.FolderBrowserDialog();
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
UserFolderLocation = dlg.SelectedPath;
}
else { }
}
Then when searching the folder for its contents I use:
try
{
folderItems = Directory.GetFiles(directory).Select(f => Path.GetFileNameWithoutExtension(f)).ToArray();
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
If I insert the path This PC\Xperia Z3 Compact\SD Card\Music as a variable then search it, it throws a System.IO.DirectoryNotFoundException.
How do I select and use a path that doesn't begin with c:, d: etc?
In the end I ended up using the shell32 library. It has the ability to handle portable devices (That both include and don't include the drive letters).
Include the reference for shell32.dll
and include the library:
using Shell32;
Then instead of using the FolderBrowserDialog I used the use the shell browse for folder. Which returns a strange path for a folder on a phone, for the phone I used to test the path looked like this:
::{20D04FE0-3AEA-1069-A2D8-08002B30309D}\\\?\usb#vid_04e8&pid_6860&ms_comp_mtp&samsung_android#6&fee689d&3&0000#{6ac27878-a6fa-4155-ba85-f98f491d4f33}\SID-{20002,SECZ9519043CHOHB01,63829639168}\{013C00D0-011B-0130-3A01-380113012901}
public int Hwnd { get; private set; }
private void button3_Click(object sender, EventArgs e)
{
Shell shell = new Shell();
Folder folder = shell.BrowseForFolder((int)Hwnd, "Choose Folder", 0, 0);
if (folder == null)
{
// User cancelled
}
else
{
FolderItem fi = (folder as Folder3).Self;
UserFolderLocation = fi.Path;
}
}
Then to select search the folder for its contents:
try
{
Folder dir = shell.NameSpace(directory);
List<string> list = new List<string>();
foreach (FolderItem curr in dir.Items())
{
list.Add(curr.Name);
}
folderItems = list.ToArray();
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
"This PC" is only there for the eyes of the user - internally it is not used at all. You can see for yourself by applying the first marked setting in Windows Explorer
Additionally Windows assigns a drive letter to every local device - it just doesn't show it by default. (use the second marked setting to check)
So in reality you have to use (assuming you phone was assigned Drive F:) something like F:\SD Card\Music\.
Possibly related: Get List Of Connected USB Devices about the ability to find a device without knowing the assigned drive letter.
The below code an attempt to try and get get an Mp3 file from the MusicLibrary
It gives me,
A first chance exception of type
'System.UnauthorizedAccessException'
occurred in AccessingPictures.exe
This is my code:
public async void getFile()
{
StorageFolder folder = KnownFolders.MusicLibrary;
try
{
sampleFile = await folder.GetFileAsync("Test1.mp3");
}
catch (FileNotFoundException e)
{
// If file doesn't exist, indicate users to use scenario 1
Debug.WriteLine(e);
}
}
private void btnRead_Click(object sender, RoutedEventArgs e)
{
getFile();
}
Wouldn't we able to access the media files?
I am able to do this using the file picker.
But it does not work while i try to access it directly.
Am i missing anything here ?
To retrieve Pictures from Camera Roll
Void GetCameraPhotos()
{
using (var library = new MediaLibrary())
{
PictureAlbumCollection allAlbums = library.RootPictureAlbum.Albums;
PictureAlbum cameraRoll = allAlbums.Where(album => album.Name == "Camera Roll").FirstOrDefault();
var CameraRollPictures = cameraRoll.Pictures
}
}
You cannot access the files unless it is in response to a user request. i.e. the user must tap a button or something and that tap logic ends up calling your code that accesses the file. If you want to get at the file afterwards, you'll need to copy it in the app's data folder.
I finally figured the issue. It was because i hadn't enabled the capabilities in the Manifest file.
It works like a charm now.
Thanks everyone.
I've already wrote my code with my try catch and extra message box but now i have to put the message box into a resource file how can i do it?
This is my code:
public void btnUpload_Click(object sender, EventArgs e)
{
try
{
// in the filepath variable we are going to put the path file that we browsed.
filepath = txtPath.Text;
if (filepath == string.Empty)
{
MessageBox.Show("No file selected. Click browse and select your designated file.");
}
}
You can just add those messages as String in your main application Resource file using the designer (Resources.resx) and then access them using Properties namespace. Let's say you add this:
ErrorNoFile | "No file selected. Click browse and select your designated file."
You can just call it like so:
MessageBox.Show(Properties.Resources.ErrorNoFile);
And if you modify the entry name in the resource file, it will be automatically refactored, at least with VS2012 which is the one I'm using. Instanciating a ResourceManager is only good if you want to keep those messages in a separate resource, otherwise it looks like an overkill to me.
// Create a resource manager to retrieve resources.
ResourceManager rm = new ResourceManager("items", Assembly.GetExecutingAssembly());
// Retrieve the value of the string resource named "filepath".
// The resource manager will retrieve the value of the
// localized resource using the caller's current culture setting.
public void btnUpload_Click(object sender, EventArgs e)
{
try
{
// in the filepath variable we are going to put the path file that we browsed.
filepath = txtPath.Text;
if (filepath == string.Empty)
{
String str = rm.GetString("welcome");
MessageBox.Show(str);
}
}
I tried codeproject help as well as MSDN but no success. Here is a copy of my test code returning an exception:
private void button2_Click(object sender, EventArgs e)
{
File.Decrypt("Text.pvf");
string[] DataFile = File.ReadAllLines("Text.pvf");
if (DataFile[5] == "6")
MessageBox.Show("Encrypt/Decrypt successful");
//Application.Exit();
}
private void button1_Click(object sender, EventArgs e)
{
string[] DataFile = new string[6];
DataFile[0] = "1";
DataFile[1] = "2";
DataFile[2] = "3";
DataFile[3] = "4";
DataFile[4] = "5";
DataFile[5] = "6";
File.WriteAllLines("Text.pvf", DataFile);
File.Encrypt("Text.pvf");
}
At the line: "File.Encrypt("Text.pvf");", I get an IOException that says: 'The request is not supported.'. Now the button1 method is called first. I do not know why this error comes up.
My pc: Windows7 64bit, .net 4.0, file system is NTFS as needed for File.Encryption method.
Please copy and paste my code to see if you can maybe spot the error. Perhaps I am missing something. Please help.
Are you using Windows 7 Home Edition?
In Windows 7 Home Edition, it is not supported.
http://www.pcreview.co.uk/forums/encrypt-contents-secure-data-greyed-out-t171160.html
Your code works on my computer running Visual Studio 2010 in a WPF App 4.0 client profile. So it must be something with your user account and permissions. Try to save the file in another directory like the IsolatedStorage