XML file can't be saved in windows mobile - c#

In simple way, I want to save some data in XML file when i tried this code it ran successfully but,unfortunately i didn't the file in the project folder or anywhere on my computer.When I changed the path also i didn't find it.
The following is the used code
string configFile = #"config.xml";
XmlDocument xml = new XmlDocument();
XmlElement element = xml.CreateElement("Configuration");
xml.AppendChild(element);
//---create the <LastAccess> element---
element = xml.CreateElement("LastAccess");
element.InnerText = DateTime.Now.ToString();
xml.DocumentElement.AppendChild(element);
//---create the <LastSearchString> element---
element = xml.CreateElement("LastSearchString");
element.InnerText = "sushi";
xml.DocumentElement.AppendChild(element);
xml.Save(configFile);
Can you help me in this problem please.
When I wrote this code and ran the application the file must be saved whatever where
XmlDocument xml = new XmlDocument();
XmlElement element = xml.CreateElement("First");
xml.AppendChild(element);
element = xml.CreateElement("Second");
element.InnerText = "LaLa";
xml.DocumentElement.AppendChild(element);
xml.Save(#"XML.xml");
and then i try this code as the file has been saved
element.InnerText = "LaLa";
xml.DocumentElement.AppendChild(element);
xml.Save(#"XML.xml");
I got that exception Could not find file '\XML.xml'.
please can you help me in this problem.

The emulator is, for all intents and purposes of this question, a completely separate device. It does not "share" any part of it's file system with the host PC, so there's no way to "browse" it's files (like the one you created" from the PC's Windows Explorer, or the standard file system APIs.
If you want access to the file from the PC, you need to use one of the following to retrieve it:
Configure the emulator to share a folder with the PC. This is don't in the options of the Emulator itself and allows you to "mount" a Host PC folder. That folder becomes the "\Storage Card" root folder in the emulator, so you'd have to change your code appropriately (i.e. save to "\storage card\config.xml")
Use a tool like Remote Registry Editor (in the Start menu under Visual Studio 22008 remote tools), connect to the emulator and download the file.
Use the Emulator Manager to "dock" the emulator so it shows up in ActiveSync/WMDC. When that occurs, a shell extension will show the device in Windows Explorer - though be aware that it is purely a shell extension. There is still no file API access to that system, so you could not write a desktop app that navigates to "My Device\MyFolder\MyFile.xml".

Related

Environment.GetFolderPath(Environment.SpecialFolder) is returning wrong value

I have a UWP project, and wrote this code:
foreach (var foldertype in (Environment.SpecialFolder[])Enum.GetValues(typeof(Environment.SpecialFolder)))
{
//string d = Environment.CurrentDirectory;
var path = Environment.GetFolderPath(foldertype);
var folder = await StorageFolder.GetFolderFromPathAsync(path);
StorageApplicationPermissions.FutureAccessList.Add(folder, folder.Path);
Debug.WriteLine($"Opened the folder: {folder.DisplayName}");
this.MenuFolderItems.Add(new MenuFolderItem(folder));
}
It is supposed to enumerate all the special folders, and get their folder. However, while debugging, this is what happens:
foldertype = Desktop
path = "C:\\Users\\cuent\\AppData\\Local\\Packages\\402b6149-1adf-4994-abc9-504111b3b972_a5s740xv383r0\\LocalState\\Desktop"
folder = [ERROR] System.IO.FileNotFoundException: 'The system cannot find the file specified. (Exception from HRESULT: 0x80070002)'
I do not know what is happening here, it seems to be appending the path to the installed location of the app. How do I fix this?
Expected output of GetFolderPath() is wherever the Desktop is, not the weird path.
UWP apps are different from desktop applications when accessing the file system. UWP apps are running in the sandbox so there are limitations for UWP apps when trying to access the file system. You could check this document: File access permissions. The document lists all the locations that UWP apps have permission to access.
Back to your scenario, what you need first is a broadFileSystemAccess restricted capability. This capability enables your app could use the StorageFolder.GetFolderFromPathAsync() API with a Path parameter. This is mentioned in the last part of the document I posted above.
Then the second issue is the Environment.GetFolderPath API. It looks like the API will return a Path that points to a local folder inside the app's local folder. But there is no such desktop folder inside the app's local folder so you will get the FileNotFoundException. You might need to set the correct path by yourself like C:\Users\your user name\Desktop. After that, your code should be able to work correctly.

Application can find 'Downloads' folder when debugging but not on IIS

I have an application that allows the user to upload a file (saving it to in a folder located in the wwwroot of the ASPNETCORE application). From here they can make edits to it and then they can choose to export the file as a csv/ xml/ xlsx which downloads the file to the user's 'downloads' folder.
While debugging in Visual Studio this all works fine however when I publish and deploy the application to IIS I am getting the exception
Error saving file C:\windows\system32\config\systemprofile\Downloads(FILE NAME)
Could not find part of the path C:\windows\system32\config\systemprofile\Downloads(FILE NAME)
This is the current way I am getting the downloads folder:
FileInfo file = new FileInfo(Path.Combine(Environment.ExpandEnvironmentVariables(#"%USERPROFILE%\Downloads"), data.Filename + "." + data.FileType));
However I have also tried the solution that Hans Passant has answered to a similar question here. Both solutions worjk fine while debugging locally however as soon as I publish them, this one produces the exception:
Value cannot be null. Parameter name: path1
Which I presume is thrown at this point here when I try and save the file to the user's download folder.
using (var package = new ExcelPackage(file))
{
var workSheet = package.Workbook.Worksheets.Add("ExportSheet");
workSheet.Cells.LoadFromCollection(exports, true);
package.Save();
}
I don't really know how I would be able to reproduce these exceptions seeing as locally using Visual Studio it all works fine.
Has anyone else came across this issue while trying to download a file?
UPDATE: When the application is running on IIS, it seems to be using that as the user profile instead of the actually user, so when it tries to navigate to the Downloads folder, it cannot find it. How can I force it to use the user's profile?
LoadUserProfile is already set to True.
Web applications have no knowledge of the end-user's computer's filesystem!
So using Environment.GetFolderPath or Environment.ExpandEnvironmentVariables in server side code will only reveal the server-side user (i.e. the Windows Service Identity)'s profile directories which is completely separate and distinct from your web-application's actual browser-based users OS user profile.
As a simple thought-experiment: consider a user running a weird alien web-browser on an even more alien operating system (say, iBrowse for the Amiga!) - the concept of a Windows-shell "Downloads" directory just doesn't exist, and yet here they are, browsing your website. What do you expect your code would do in this situation?
To "download" a file to a user, your server-side web-application should serve the raw bytes of the generated file (e.g. using HttpResponse.TransmitFile) with the Content-Disposition: header to provide a hint to the user's browser that they should save the file rather than try to open it in the browser.

Xamarin Android 16 Jelly Bean / 4.1 create folder and file

I know c#; have developed for windows mobile; I now have an android project with constraints that I cannot change; the most important being cannot run above API 16 due to the devices the app will be running on. These devices are already purchased. I’m aware of the age of these devices, and how old 4.1 is; hands tied.
I’ve started a new Xamarin (not forms) project for android only; compile using 8.1 Oreo; Min version 4.1, target version 8.1. I’m aware this is not ideal however doing so I’ve managed to get lots of other needed features working including camera and barcode scanner. Changing compile version down to 4.1 causes numerous errors which won’t compile.
I’m testing the device using usb-debugging on the actual device and even though it’s 4.1, the code runs and features work – camera, scanner etc.
I’m stuck trying to create a folder and then write/read a file in that folder. I’d like this folder to be accessible via windows explorer when plugged into computer.
I’ve got code like this to write a file:
string FileContents = "Text file contents";
Java.IO.File SaveFolder = new Java.IO.File(Android.OS.Environment.GetExternalStoragePublicDirectory("Documents") + Java.IO.File.Separator + "FolderName");
Boolean Success = false;
if (!SaveFolder.Exists())
{
Success = SaveFolder.Mkdirs();
}
string FName = "test.txt";
string FTogether = System.IO.Path.Combine(SaveFolder.Path, FName);
Java.IO.FileWriter fw = new Java.IO.FileWriter(FTogether);
fw.Write(FileContents);
fw.Close();
SaveFolder.Dispose();
And code like this to read the file:
Java.IO.File SaveFolder = new Java.IO.File(Android.OS.Environment.GetExternalStoragePublicDirectory("Documents") + Java.IO.File.Separator + "FolderName");
string FName = "test.txt";
string FTogether = System.IO.Path.Combine(SaveFolder.Path, FName);
StreamReader sr = new StreamReader(FTogether);
string FileContents = sr.ReadToEnd();
Debugging reveals SaveFolder’s AbsolutePath to be /storage/sdcard0/Documents/FolderName
I think this is part of the android’s internal storage which the app has access to but nothing else.
How do I get a folder which is accessible from outside the app ?
Environment.DirectoryDocuments
cannot be used because it’s null at runtime on API 16.
The path you have is actually publicly accessible so it's not specific to your application. When you connect your Android device to the computer, you should be able to go to the root folder of the device and see the Documents folder.
Don't let the /storage/sdcard0/ part in the beginning of the path confuse you. For historical reasons, Android simulates an sdcard even if there isn't one physically on the device. In reality, /storage/sdcard0/ is just a symlink to /data/media/0.
For a really good overview of Android storage, I'd recommend you read this very thorough Reddit post: Let's clear up the confusion regarding storage in Android once and for all, including adoptable storage in Marshmallow.
What you can also do is download a file explorer app (in case your phone doesn't already have one) and go to the Documents folder. You should see FolderName there.
Edit: Since you're running on such an old version of you might also suffer from the bug in the MTP protocol, which causes newly created files and folders to be invisibile when attaching the device to a computer via USB.
The fix is to call MediaScannerConnection.scanFile for each new file/folder you've created, as explained here.

Physical file path issue in c#

I have a file which is stored at a physical disk say var path = file://Servername/SampleFiles/abc.docx. Now when I am trying to add this into below code
File.SetAttributes(path, FileAttributes.ReadOnly);
With above line of code I am getting URI file format is not supported whereas if I am trying to add path like var path = //Servername/SampleFiles/abc.docx then above line is working fine but I am getting a prompt on Internet Explorer as Only Secure content is displayed
Please guide guide me to remove the IE prompt, I don't want users to disable it from IE, as it will be security issues.

A default path when downloading PDF file in computer/mobile phone

I created a PDF webapp where users are able to generate various type of PDF on both the computer and mobile phone. However, i run my program on a localhost and this is how i save my PDF based on my computer's file directory
var output = new FileStream(Path.Combine("C:\\Users\\apr13mpsip\\Downloads", filename), FileMode.Create);
However, when i publish my webapp onto azure, i wasn't able to download from both my computer and mobile phone. Therefore i believe that it could be due to my default file directory.
Hence i would like to ask how to do a default file directory for all computer and mobile phone?
Or could it be i left out something that is necessary when the webapp is published online
Thanks.
PS : I hardcoded a default file path in order for me to test my application on a localhost to ensure a perfect working condition. Therefore i'm finding a way to find a default common file directory for all mobile/computer users when they attempt to download the PDF instead of my usual hard-coded file path
UPDATE
I tried using the method Server.MapPath but receive some error.
var doc1 = new Document();
var filename = Server.MapPath("~/pdf") + "MyTestPDF" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".pdf";
// var output = new FileStream(Path.Combine("C:\\Users\\apr13mpsip\\Downloads", filename), FileMode.Create);
//iTextSharp.text.pdf.PdfWriter.GetInstance(doc1, output);
using (var output = File.Create(filename))
{
iTextSharp.text.pdf.PdfWriter.GetInstance(doc1, output);
}
doc1.Open();
This is the error i received
ObjectDisposedException was unhandled by user code
Cannot access a closed file.
When you write a Web Application you shall never use hard coded paths, and the last place where you should save files is C:\Users !! It does not matter whether this is Azure or not. It is general rule for any kind of web applications!
In your case I suggest that you create a folder within your application named pdf or something like that and save files there with the following code:
var fileName = Server.MapPath("~/pdf") + filename;
using (var output = File.Create(fileName) )
{
// do what you want with that stream
// usually generate the file and send to the end user
}
However there is even more efficient way. Use the Response.OutputStream and write the resulted PDF directly to the response. Will save you a lot of space on the local server, and the logic to delete unused generated files.

Categories