So basically I'm using Visual Studio and I'm trying to get it so when the user clicks on a button, it opens a directory or program although I need it to detect the current user, so that it doesn't open my users files.
There are so many ways in .Net to get the current user. The most common answer you will find is String UserName = Environment.UserName;
Related
Hello fellow developers,
I'm trying to give a C# application that I'm creating the ability to delete the files from a flash-drive or other folder, for which admin priv is needed. But it's not working!
I am an admin user on my Win10 box. I can delete the files in File Explorer. But the program throws an IOException when it tries to do it (I'm using any of several methods to delete the files, including interoping to Win32).
I did create and embed an Application Manifest for the program project (I'm using Visual Studio 2017), and set the level attribute of the requestedExecutionLevel element to "requireAdministrator". And within the project-properties it does show this file, app.manifest, as part of it. But that seems to accomplish nothing -- the program can still be launched NOT as administrator.
Btw, I see two different methods to detect whether the program is running as with administrator priv:
public bool IsRunAsAdmin1()
{
return Thread.CurrentPrincipal.IsInRole( WindowsBuiltInRole.Administrator.ToString() );
}
This does NOT seem to be working (always returning false).
and..
public bool IsRunAsAdmin2()
{
WindowsIdentity id = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal( id );
return principal.IsInRole( WindowsBuiltInRole.Administrator );
}
which does work.
Regardless, even when I right-click on the program and run it as administrator -- it returns Win32 error 5 (access denied) for Hidden files.
I want to make this delete files robustly, regardless of the file's attributes. How can I do this?
Thank you for your help and insights, James
I'm not sure what do you mean by
the program can still be launched NOT as administrator.
If you setup the app.manifest file properly (see this) then it always will be running as administrator.
I'm not sure about the hidden files. My quick advice would be just to remove the hidden/readonly flag (like this) and then call File.Delete.
trying to upload a file to an already created folder but this error keeps coming
Access to the path 'C:\Users\Joe\Documents\Visual Studio
2015\Projects\training\Site1\Site1\Content\ProductImages' is denied.
and then below is this
Exception Details: System.UnauthorizedAccessException: Access to the
path 'C:\Users\Joe\Documents\Visual Studio
2015\Projects\training\Site1\Site1\Content\ProductImages' is denied.
ASP.NET is not authorized to access the requested resource. Consider
granting access rights to the resource to the ASP.NET request
identity. ASP.NET has a base process identity (typically
{MACHINE}\ASPNET on IIS 5 or Network Service on IIS 6 and IIS 7, and
the configured application pool identity on IIS 7.5) that is used if
the application is not impersonating. If the application is
impersonating via , the identity will be
the anonymous user (typically IUSR_MACHINENAME) or the authenticated
request user.
To grant ASP.NET access to a file, right-click the file in File
Explorer, choose "Properties" and select the Security tab. Click "Add"
to add the appropriate user or group. Highlight the ASP.NET account,
and check the boxes for the desired access.
Source Error:
Line 73: var path = Server.MapPath("~/Content/ProductImages"); // guardo en la variable path la direccion donde quiero guardar las imagenes, este path es un string que tu lo conformas segun el interes, puedeser upload/nombre_fichero/fecha/etc
Line 74: string pathdir = Path.Combine(path, imageName);
*Line 75: file.SaveAs(path); // store file*
Line 76: var imagen = new Image();
Line 77: imagen.ImagePath = pathdir;
and line 75 is in red
When checking the granted rigths there is no restriction for storing or in the file to be stored
The security is coming from the OS, not the compiler. Navigate to your folder in Windows, right-click, change security.
If deploying, be sure to use a folder that is automatically granted write permissions to .NET - like the User/Appdata/Roaming folder.
EDIT:
You are saying you've added EVERYONE to the folder and given them full control but are still getting no joy. Please try this test:
private static void writeText()
{
using (TextWriter tw = new StreamWriter(#"C:myTestFile.txt"))
{
tw.WriteLine("Hello World",false);
tw.Close();
}
}
Run the above from your solution, then check you DEBUG folder for your solution (I've forgotten at this point if we're dealing with console or form or web, so you may have to search your computer for the mytestFile.txt file after running).
The point in running this is that C: (with no backslash) points to your project folder and will automatically have adequate permissions for write. If this works and you get a mytestFile.txt after running, then we go in one direction. If you get an access error, we go in another direction. So please run in your solution or a new console app (your solution would be best) and report back with the results. Have patience buddy - we'll do the best we can to get you where you need to be!
When you host an application in IIS, IIS will run the application under another user name depending on your application pool settings. It is a good idea to know the Application Pool (What is an IIS application pool?), but in your specific case, you do not have to go through the learning curving.
The easiest way is to figure out the actual user name IIS is using by printing out the System.Environment.UserName and grant this user to the directory you want it to access.
The file permission error is coming from your Windows OS Explorer.
It gives you the exact fix:
To grant ASP.NET access to a file, right-click the file in File Explorer, choose "Properties" and select the Security tab. Click "Add" to add the appropriate user or group. Highlight the ASP.NET account, and check the boxes for the desired access.
Give this a shot.
Try to check the Sharing type of the folder.
Right click->Properties->Sharing Tab->Click Share... Buttong->Then Choose Everyone then add Then change it to read and write.
Then test your program again.
if error still exist try to add the folder to your solution explorer.
Click Solution Explorer->Show All files->Then Find the folder where it was then Include in the project.
Just give it a try.
We have to give write permissions to "IIS_Users" for folder "ProductImages" which are trying to upload, since IIS used this user to access your upload folder.
Please see here how to add IIS_Users to your folder.
Hope this helps you.
Check the permission of that folder, right click on the folder, remove selection from the check box next to "Read Only", then click on "Security" => "Edit" => Select "Users" and tick the check box for "Full Control" and "Apply"
I'm currently developing a C# WinForms application in VS2012 (.NET 4.0). The application is a bit like an Email client and displays a list of messages. And each message can have one or one files attached.
The file attachments are stored on a different server, which can only be accessed using another user account (and not by the logged on user).
When the user double clicks on a File Attachment I need to open the file and display it in the associated application. i.e. TXT files in Notepad, DOCX files in Word, etc.
I was hoping I could just pass the full file name into the System.Diagnostics.Process.Start method, with the correct username, password and domain values and it would open the file in the associated application.
e.g.
SecureString password = new SecureString();
"MyPassword".ToCharArray().ToList().ForEach(password.AppendChar);
System.Diagnostics.Process.Start(#"\\MyServer\MyFolder\MySubFolder\MyFile.docx",
"MyUsername",
password,
"MyDomain");
But an exception is thrown with the message:
The specified executable is not a valid application for this OS platform.
I've also tried creating a ProcessStartInfo object instance and setting the FileName property to "Explorer.exe" and the Arguments property to #"\\MyServer\MyFolder\MySubFolder\MyFile.docx", and passing it as the parameter into the System.Diagnostics.Process.Start method. But this doesn't work either. No exception is thrown and the file isn't displayed either.
But if you look at the object returned by the System.Diagnostics.Process.Start method you see that an InvalidOperationException has occurred.
My C# question is, how can I open and display a file (in it's associated application), when the file is stored on a server that can only be accessed using different user credentials?
I think this should work
Step 1. Find the App registered with the extension
Step 2. Use the same Api that was mentioned
System.Diagnostics.Process.Start("App from the current Machine that was found in step 1",
#"\MyServer\MyFolder\MySubFolder\MyFile.docx",
"MyUsername",
password,
"MyDomain");
See the following links of how to find the register app for an extension
How to get recommended programs associated with file extension in C#
http://www.codeproject.com/Articles/17023/System-File-Association
I'm working on a online only winform application which I deploy using ClickOnce feature it uploads through FTP to the server and the user executes it online through http.
As you may already know, the Online only feature doesn't place any icons on the desktop, so everytime it runs the user got to run the setup.exe file to do it.
My question is, if there is anyway I could actually create an icon that may point to the setup file or any workaround to make sure the user got an accesible and easy way to run the app without having to look for the setup file everytime?
Users may not know a lot about computers so it can be a hard task to navigate all the way to the downloaded file everytime, and I want to make it easier for them.
I know that if I do an offline/online app it will solve the problem, but I would like it to be online only.
Any ideas?
you can create desktop shortcut manually on the first app run, and point it to either to your app's url, or path to downloaded file (I guess, url will be safer in case user deletes the file). Code can look something like this (need adjusting to your URL):
void CheckForShortcut()
{
ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment;
if (ad.IsFirstRun)
{
Assembly code = Assembly.GetExecutingAssembly();
string company = string.Empty;
string description = string.Empty;
if (Attribute.IsDefined(code, typeof(AssemblyCompanyAttribute)))
{
AssemblyCompanyAttribute ascompany = (AssemblyCompanyAttribute)Attribute.GetCustomAttribute(code,
typeof(AssemblyCompanyAttribute));
company = ascompany.Company;
}
if (Attribute.IsDefined(code, typeof(AssemblyDescriptionAttribute)))
{
AssemblyDescriptionAttribute asdescription = (AssemblyDescriptionAttribute)Attribute.GetCustomAttribute(code,
typeof(AssemblyDescriptionAttribute));
description = asdescription.Description;
}
if (company != string.Empty && description != string.Empty)
{
string desktopPath = string.Empty;
desktopPath = string.Concat(Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
"\\", description, ".appref-ms");
string shortcutName = string.Empty;
shortcutName = string.Concat(Environment.GetFolderPath(Environment.SpecialFolder.Programs),
"\\", company, "\\", description, ".appref-ms");
System.IO.File.Copy(shortcutName, desktopPath, true);
}
}
}
credits to http://geekswithblogs.net/murraybgordon/archive/2006/10/04/93203.aspx
What is your reason for wanting an online only ClickOnce app? I always recommend offline unless your app is really an edge case.
There's very little difference between online and offline. All the same files are downloaded to the same location on the client. Offline apps add an entry to the 'Add/Remove Programs', a start menu shortcut, and an optional desktop shortcut (if you are targeting .NET 3.5+). The ability to uninstall through Add/Remove Programs is key. It makes supporting your application much easier when users have install problems.
Also, you mention users running the setup.exe every time. This is unnecessary. The setup.exe will contain your bootstrapped pre-requisites and then launch the app when it finishes. If the user has run the setup.exe once, they only need to click the link to the .application file. That will definitely speed up the app's start time. Also, in many cases the user has to have admin privileges to run the setup.exe; clicking the .application doesn't (assuming someone with admin privileges has already run the setup.exe).
In conclusion, there really isn't an answer here :). But...
Make absolutely sure your reasoning is sound for not doing an offline install instead.
After running the setup.exe once, direct users to click on the .application url (or the desktop shortcut if you switch to offline) instead of the setup.exe.
As far as I know, there is no reliable way for running online only ClickOnce application than creating shortcut to that setup.exe.
I have an automation addin for excel developed using C#. How do I package and distribute it ? Also when the addin is installed for the first time, I want a username and password check to pop for the first time.
How can I go about doing this ?
thanks
Visual Studio creates a setup project for each Add-in project. You could start by using that. It produces an MSI file that you can distribute.
About the second part - if you stay with Studio-generated setup you probably cannot add custom dialogs to installation. You'll need some tool that builds the installations.
How about asking for username and password on the first use? This way the installation remains simple. In my experience every question during installation increases the risk that the user says "WTF, why do I have to answer these stupid questions. Cancel".
To ask for username and password on the first use only you have to save them somewhere after asking, so that next time you know them. Approved Microsoft way is saving them in Settings. By default Studio creates Settings file in your peoject just for that. Just add two variables to that file with empty default values. Mark them as User variables (not the Application variables).
From your add-in, access them as Properties.Setings.VariableName.
When your add-in starts, check if you have the username and password in settings. If they are empty, ask and save.
if (string.IsNullOrEmpty(Properties.Settings.Default.UserName))
{
string name;
string password;
//ask for name and password, replace with your code
AskForUserandPassword(out name, out password);
Properties.Settings.Default.UserName=name;
Properties.Settings.Default.Password=password;
Properties.Settings.Default.Save()
}
Physically, this is saved somewhere deep in user directory in an XML file.