Access to the path is denied in Windows Store application - c#

I create Windows Store application. In MainPage.xaml.cs I want to get data from xml file, but I get error message on line:
XDocument document = XDocument.Load(filename).
UnauthorizedAccessException was unhandled by user code
Access to the path 'C:\Events Project\events.xml' is denied.
Any advice is appreciated.
MainPage.xaml.cs
private EventMan man = new EventMan();
public MainPage()
{
this.InitializeComponent();
this.LoadEvents();
}
private void LoadEvents()
{
this.Events = man.GetAllEvents(#"C:\Events Project\events.xml");
}
EventMan.cs
public List<Event> GetAllEvents(string filename)
{
if (filename == null)
{
throw new ArgumentNullException("filename");
}
XDocument document = XDocument.Load(filename);
...
}

You can only access certain locations with Windows Store apps by default, as explained here:
File access and permissions in Windows Store apps
You can put the file in your app's AppData folder. Then you can use the ApplicationData class to freely access the file from there...
var file = await ApplictionData.Current.LocalFolder.GetFileAsync("events.xml");

Related

Error: File operation not allowed. Access to route denied

I am working on a project that uses Silverlight, where I want to show PDFS files of a server path, but when I start debugging my code I find the following exception:
where I generate the flow in the following code:
System.Windows.Browser.HtmlElement myFrame = System.Windows.Browser.HtmlPage.Document.GetElementById("_sl_historyFrame");
if (myFrame != null)
{
DirectoryInfo folderPath = new DirectoryInfo(#"\\192.168.1.216\UploadFileMobilePDF\" + transfer.IdTransfer);
foreach (var file in folderPath.EnumerateFiles("*.pdf", SearchOption.AllDirectories))
{
myFrame.SetStyleAttribute("width", "1024");
myFrame.SetStyleAttribute("height", "768");
Uri uri = new Uri(folderPath + file.FullName);
string path = uri.AbsoluteUri.ToString();
myFrame.SetAttribute("src", path);
myFrame.SetStyleAttribute("left", "0");
myFrame.SetStyleAttribute("top", "50");
myFrame.SetStyleAttribute("visibility", "visible");
}
}
The error marks me when instantiating the DirectoryInfo class folderPath = new DirectoryInfo ()
I don't know if silverlight can't have permissions to server addresses
Your application likely doesn't have permission to access the files on the server you're trying to access.
Look into WindowsImpersonationContext for the most likely way around this. https://learn.microsoft.com/en-us/dotnet/api/system.security.principal.windowsimpersonationcontext?view=netframework-4.8
You'll want a class (say, "MyImpersonator") that uses WindowsImpersonationContext to log onto the server using valid credentials. There are too many details to present an entire solution, but using the class (defined elsewhere) to get a single file might look something like this:
using (var impersonator = new MyImpersonator())
{
string name = ConfigurationManager.AppSettings["name"];
string password = ConfigurationManager.AppSettings["pass"];
if (impersonator.LogOnCrossDomain(account, pass))
{
if (File.Exists(filepath))
{
byte[] content = File.ReadAllBytes(filepath);
}
}
}

Opening a document from Imanage in Word 2016

I am attempting to open an Imanage document, in MS Word, within a temporary test application (for debugging) to later copy over into an ActiveX control project. The error that is popping up is:
Exception thrown at 0x7618851A (msvcrt.dll) in w3wp.exe: 0xC0000005: Access >violation reading location 0x09801000.
If there is a handler for this exception, the program may be safely continued.
The error occurs when running the cmd.Execute line and I am unsure as to why I am getting the error.
using IManage;
using IMANEXTLib;
using System;
namespace WebApplication3
{
public partial class WebForm2 : System.Web.UI.Page
{
IManDatabase imanagedatabase;
IManDMS myDMS = new ManDMSClass();
protected void Page_Load(object sender, EventArgs e)
{
openImanageDoc("docNumber", "versionNumber", "server", "database", ReadOnly);
}
public void imanageLogin(string server, string database)
{
try
{
IManSession session = myDMS.Sessions.Add(server);
IManWorkArea oWorkArea = session.WorkArea;
session.TrustedLogin();
foreach (IManDatabase dbase in session.Databases)
{
if (dbase.Name == database)
{
imanagedatabase = dbase;
}
}
}
catch (Exception ex)
{
throw ex;
}
}
public void openImanageDoc(string docNo, string versionNo, string server, string database, bool isReadOnly = true)
{
IManDocument doc;
try
{
imanageLogin(server, database);
int iDocNo = int.Parse(docNo);
int iVersion = int.Parse(versionNo);
doc = imanagedatabase.GetDocument(iDocNo, iVersion);
openNRTDocument(ref doc, isReadOnly);
imanagedatabase.Session.Logout();
myDMS.Close();
}
catch (Exception Ex)
{
imanagedatabase.Session.Logout();
throw Ex;
}
finally
{
imanagedatabase = null;
myDMS = null;
}
}
public void openNRTDocument(ref IManDocument nrtDocument, Boolean isReadonly)
{
OpenCmd cmd = new OpenCmd();
ContextItems objContextItems = new ContextItems();
objContextItems.Add("NRTDMS", myDMS);
objContextItems.Add("SelectedNRTDocuments", new[] { (NRTDocument)nrtDocument.LatestVersion });
objContextItems.Add("IManExt.OpenCmd.Integration", false);
objContextItems.Add("IManExt.OpenCmd.NoCmdUI", true);
cmd.Initialize(objContextItems);
cmd.Update();
cmd.Execute();
}
}
}
Due to the nature of the error, I am presuming it is a configuration issue rather than a code error although I could be completely wrong as I am very new to programming.
I have found out that w3wp.exe is an IIS worker process created by the app pool but other than that I have no idea what the numeric code represents. Any help or advice is greatly appreciated.
The error is being raised by the OpenCmd instance because it is most likely trying to access resources such as local registry settings. It's not possible to do that in a web application, unless you host your code in a proprietary technology like ActiveX (which is specific to Internet Explorer)
Actually, it is not appropriate for you to use OpenCmd here. Those type of commands (iManage "ICommand" implementations) are intended to be used in regular Windows applications that have either the iManage FileSite or DeskSite client installed. These commands are all part of the so-called Extensibility COM libraries (iManExt.dll, iManExt2.dll, etc) and should not be used in web applications, or at least used with caution as they may inappropriately attempt to access the registry, as you've discovered, or perhaps even display input Win32 dialogs.
For a web app you should instead just limit yourself to the low-level iManage COM library (IManage.dll). This is in fact what iManage themselves do with their own WorkSite Web application
Probably what you should do is replace your openNRTDocument method with something like this:
// create a temporary file on your web server..
var filePath = Path.GetTempFileName();
// fetch a copy of the iManage document and save to the temporary file location
doc.GetCopy(filePath, imGetCopyOptions.imNativeFormat);
In an MVC web application you would then just return a FileContentResult, something like this:
// read entire document as a byte array
var docContent = File.ReadAllBytes(filePath);
// delete temporary copy of file
File.Delete(filePath);
// return byte stream to web client
return File(stream, MediaTypeNames.Application.Octet, fileName);
In a Web Forms application you could do something like this:
// set content disposition as appropriate - here example is for Word DOCX files
Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
// write file to HTTP content output stream
Response.WriteFile(filePath);
Response.End();

How to allow usage of FilePicker in WindowsStore App?

Using c#, Windows Store App, VS 2013
Try to open File Picker, using next simple code:
private async void OkBtnClick(IUICommand command)
{
if (this.EnsureUnsnapped())
{
FileOpenPicker fop = new FileOpenPicker();
fop.FileTypeFilter.Add(".png");
fop.FileTypeFilter.Add(".jpg");
fop.FileTypeFilter.Add(".jpeg");
fop.ViewMode = PickerViewMode.Thumbnail;
fop.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
StorageFile requestedFile = await fop.PickSingleFileAsync();
if (requestedFile != null)
{
//TODO:
}
}
}
internal bool EnsureUnsnapped()
{
// FilePicker APIs will not work if the application is in a snapped state.
// If an app wants to show a FilePicker while snapped, it must attempt to unsnap first
bool unsnapped = ((ApplicationView.Value != ApplicationViewState.Snapped)
|| ApplicationView.TryUnsnap());
if (!unsnapped)
{
Extensions.NotifyUser("Cannot unsnap app...", statusNotificationBlock);
}
return unsnapped;
}
Also add capability in appmanifest file for Pictures Library:
But during running got exception : System.UnauthorizedAccessException on line StorageFile requestedFile = await fop.PickSingleFileAsync();.
Question: Why I got this exception if all required access provided, Also i try to launch VS2013 with Administrator rights - result - same.
For creating this code use this article

Server file access XML

I have been testing my code to save into an XML file locally and it is working fine. However i have just uploaded it to my server and it is not working. I changed the path to the path of the xml file but still no luck. This is my local code...
public void AddNodeToXMLFile(string XmlFilePath, string NodeNameToAddTo)
{
//create new instance of XmlDocument
XmlDocument doc = new XmlDocument();
//load from file
doc.Load(XmlFilePath);
//create main node
XmlNode node = doc.CreateNode(XmlNodeType.Element, "Level", null);
//create the nodes first child
XmlNode mapname = doc.CreateElement("map");
//set the value
mapname.InnerText = mapsave.Value;
// add childes to father
node.AppendChild(mapname);
// find the node we want to add the new node to
XmlNodeList l = doc.GetElementsByTagName(NodeNameToAddTo);
// append the new node
l[0].AppendChild(node);
// save the file
doc.Save(XmlFilePath);
}
protected void btnSave_Click(object sender, EventArgs e)
{
if (mapsave.Value.ToString() == "")
{
lblResult.Text = lblError.Value;
}
else
{
AddNodeToXMLFile("C:\\Users\\Glen.Robson\\Documents\\Visual Studio 2010\\Projects\\Project1\\Project1\\Scripts\\UserMaps.xml", "TileMaps");
}
}
So when i uploaded to the server i changed the path of AddNodeToXMLFile() to:
"http://www.mydomain.com/Scripts/UserMaps.xml"
But this does not work... Can anyone tell me what the file path should be?
You cannot change the path to a URL... the code on the server still needs to know the physical path to the file on the server. It cannot work out where the file is based on a URL.
Why don't you use an application specific path...
AddNodeToXMLFile(VirtualPathUtility.ToAbsolute("~/Scripts/UserMaps.xml"),"TileMaps");
Then in your function, you need to "map" the virtual path into an actual physical path on the server...
public void AddNodeToXMLFile(string XmlFilePath, string NodeNameToAddTo)
{
XmlFilePath = Server.MapPath(XmlFilePath);
...
Also, you need to make sure that permissions are setup on the server correctly - meaning that the process that the ASP.NET application is running on IIS with, has the ability to write to the directly
In a nutshell: What you are asking cannot be done. If you want to change content on your server, you need to have a program or a script on the server that handles your request. Only a program/script that is executed on the server is able to change files on the server.

C# Path Problem

I have this file: C:\Documents and Settings\extryasam\My Documents\Visual Studio 2010\Projects\FCR\WebApplication4\config\roles.txt and I want to import it into my C# application. If I insert the full path it's ok, but I want to do something similar to what we do with websites, and that is "\config\roles.txt"
However with the below code, this is not working.
This is my code:
public string authenticate()
{
WindowsIdentity curIdentity = WindowsIdentity.GetCurrent();
WindowsPrincipal myPrincipal = new WindowsPrincipal(curIdentity);
//String role = "NT\\Internet Users";
//string filePath = Server.MapPath("config/roles.txt");
//string filePath = (#"~/WebApplication4/config/roles.txt");
//string filePath = Path.GetDirectoryName(#"\config\roles.txt");
string filePath = Path.GetPathRoot(#"/config/roles.txt");
string line;
string role = "";
if (File.Exists(filePath))
{
StreamReader file = null;
try
{
file = new StreamReader(filePath);
while ((line = file.ReadLine()) != null)
{
role = line;
}
}
finally
{
if (file != null)
{
file.Close();
}
}
}
if (!myPrincipal.IsInRole(#role))
{
return "401.aspx";
}
else
{
return "#";
}
}
In ASP.NET, you can use ~/config/roles.txt - in combination with Server.MapPath(), you can get the full path.
[...] ASP.NET includes the Web application root operator (~), which
you can use when specifying a path in server controls. ASP.NET
resolves the ~ operator to the root of the current application. You
can use the ~ operator in conjunction with folders to specify a path
that is based on the current root.
(see http://msdn.microsoft.com/en-us/library/ms178116.aspx)
So you could try the following:
string filePath = System.Web.HttpContext.Current.Server.MapPath("~/config/roles.txt");
You can use Server.MapPath to map the specified relative or virtual path to the corresponding physical directory on the server.
Since you are working locally you can use absolute path to that file and it's will works.
But what about situation when web application that contains roles.txt file will be deployed on some web server and user will try to access this file from another machine?
You can use the approach below to access file hosted on a web server from a Windows application:
using (var stream = new WebClient().OpenRead("your_web_application_root_url/configs/roles.txt"))
using (var reader = new StreamReader(stream))
{
Console.WriteLine(reader.ReadToEnd());
}
Be warned that share security settings over network is not quite good idea.
You should select your file and press F4, and choose copy to output directory. Then you will be able to work with it
You could try embedding the file as a resource in your project. Something like this: How to embed a text file in a .NET assembly?

Categories