My C# project saves some machine data in an XML file. I want to show this data in an HTML website in the network. I create the XML file like so:
StorageFile file = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync(
"history.xml",
CreationCollisionOption.ReplaceExisting);
using (IRandomAccessStream writeStream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
System.IO.Stream s = writeStream.AsStreamForWrite();
XmlWriterSettings historyXMLwriterSettings = new XmlWriterSettings();
historyXMLwriterSettings.Indent = true;
historyXMLwriterSettings.IndentChars = " ";
historyXMLwriterSettings.CloseOutput = true;
historyXMLwriterSettings.Async = true;
XmlWriter historyXMLwriter = XmlWriter.Create(s, historyXMLwriterSettings);
XmlSerializer historyXMLserializer = new XmlSerializer(typeof(List<Auftrag>));
historyXMLserializer.Serialize(historyXMLwriter, auftragsliste);
await historyXMLwriter.FlushAsync();
}
My problem is that I need the file history.xml in the second project "webserver" in the public folder. How can I create the file directly in this folder or copy it?
Related
I am developing an application for the HoloLens 2 with Unity. I am still very confused how to connect the UWP environment and the .NET API.
I want to read text files (.txt) as well as binary files (.raw). When working on the Hololens (UWP environment) i use from Windows.Storage the FileOpenPicker(). I have currently coded the processing of the files so that I can test them in the Unity editor (.NET environment). Therefore i use File.ReadAllLines(filePath) to get the txt File and get every line as String, for the Binary Files i use FileStream fs = new FileStream(filePath, FileMode.Open) and BinaryReader reader = new BinaryReader(fs). The Method File.ReadAllLines() from System.IO does not work on the Hololens and i imagine the File stream and the Binary reader will not work as well.
So my Questions is how can i load the data when using the Hololens through the specific UWP API and then use the System.IO API for the rest?
Example of picking files (to get path for later readers):
#if !UNITY_EDITOR && UNITY_WSA_10_0
UnityEngine.WSA.Application.InvokeOnUIThread(async () =>
{
var filepicker = new FileOpenPicker();
filepicker.FileTypeFilter.Add("*");
var file = await filepicker.PickSingleFileAsync();
UnityEngine.WSA.Application.InvokeOnAppThread(() =>
{
path = (file != null) ? file.Path : "Nothing selected";
name = (file != null) ? file.Name : "Nothing selected";
Debug.Log("Hololens 2 Picker Path = " + path);
}, false);
}, false);
#endif
#if UNITY_EDITOR
OpenFileDialog openFileDialog1 = new OpenFileDialog();
path = openFileDialog1.FileName;
...
#endif
EDIT:
To make it more clear i have another class which uses the file path (from the picker) and reads the file, depending on the extension (.txt, .raw), as text file or binary file with the help of the System.IO methods.
// For text file
string[] lines = File.ReadAllLines(filePath);
string rawFilePath = "";
foreach (string line in lines)
{
}
// For binary file
FileStream fs = new FileStream(filePath, FileMode.Open);
BinaryReader reader = new BinaryReader(fs);
But on the Hololens 2 the File.ReadAllLines(filePath) throws a DirectoryNotFoundException: Could not find a part of the path Exception. Can i use the Windows.Storage.StorageFile and change it so it works with the code which uses the System.IO methods?
I think i found an Answer and i hope it helps others with the same problem:
#if !UNITY_EDITOR && UNITY_WSA_10_0
public async Task<StreamReader> getStreamReader(string path)
{
StorageFile file = await StorageFile.GetFileFromPathAsync(path);
var randomAccessStream = await file.OpenReadAsync();
Stream stream = randomAccessStream.AsStreamForRead();
StreamReader str = new StreamReader(stream);
return str;
}
#endif
With this code i can get a stream from an Windows StorageFile and generate a StreamReader or a BinaryReader through which i can use the rest of my calculations written with System.IO.
While trying to upload files to SharePoint online, remotely via SharePointClient upload, I am encountering a file size limit of 2mb. From my searches it seems that people have overcome this limit using PowerShell, but is there a way to overcome this limit using the native SharePointClient package in .Net C#? Here is my existing code sample:
using (var ctx = new Microsoft.SharePoint.Client.ClientContext(httpUrl))
{
ctx.Credentials = new Microsoft.SharePoint.Client.SharePointOnlineCredentials(username, passWord);
try
{
string uploadFilename = string.Format(#"{0}.{1}", string.IsNullOrWhiteSpace(filename) ? submissionId : filename, formatExtension);
logger.Info(string.Format("SharePoint uploading: {0}", uploadFilename));
new SharePointClient().Upload(ctx, sharePointDirectoryPath, uploadFilename, formatData);
}
}
I have read from the following site that you can use the ContentStream just not sure how that maps to SharePointClient (if at all):
https://msdn.microsoft.com/en-us/pnp_articles/upload-large-files-sample-app-for-sharepoint
UPDATE:
Per the suggested solution I now have:
public void UploadDocumentContentStream(ClientContext ctx, string libraryName, string filePath)
{
Web web = ctx.Web;
using (FileStream fs = new FileStream(filePath, FileMode.Open))
{
FileCreationInformation flciNewFile = new FileCreationInformation();
// This is the key difference for the first case - using ContentStream property
flciNewFile.ContentStream = fs;
flciNewFile.Url = System.IO.Path.GetFileName(filePath);
flciNewFile.Overwrite = true;
List docs = web.Lists.GetByTitle(libraryName);
Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(flciNewFile);
ctx.Load(uploadFile);
ctx.ExecuteQuery();
}
}
Still not quite working, but will update again when it is successful. Current error is :
Could not find file 'F:approot12-09-2017.zip'.
FINALLY
I am using files from Amazon S3 so the solution was to take my byte data and to stream that to the call:
public void UploadDocumentContentStream(ClientContext ctx, string libraryName, string filename, byte[] data)
{
Web web = ctx.Web;
FileCreationInformation flciNewFile = new FileCreationInformation();
flciNewFile.ContentStream = new MemoryStream(data); ;
flciNewFile.Url = filename;
flciNewFile.Overwrite = true;
List docs = web.Lists.GetByTitle(libraryName);
Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(flciNewFile);
ctx.Load(uploadFile);
ctx.ExecuteQuery();
}
You can use FileCreationInformation to create a new file and provide the contents via a FileStream. You can then add the file to the destination library. This should help you get around 2mb limit you are encountering with upload method you are using. Example below:
FileCreationInformation newFile = new FileCreationInformation
{
Url = fileName,
Overwrite = false,
ContentStream = new FileStream(fileSourcePath, FileMode.Open)
};
var createdFile = list.RootFolder.Files.Add(newFile);
ctx.Load(createdFile);
ctx.ExecuteQuery();
In the example the destination library is list you will need to get reference to this first. I can show you how to do this if required.
I need to save the file when method OnDestroy is called and load same file when method OnCreate is called. At this time I can read json file easily from Assets (this works fine)
StreamReader reader = new StreamReader(Assets.Open("reiksmes.json"));
string JSONstring = reader.ReadToEnd();
Daiktai myList = JsonConvert.DeserializeObject<Daiktai>(JSONstring);
items.Add(myList);
, but I have some problems when I try to save(write) Daiktai class data to the same file I opened above. I tried:
string data = JsonConvert.SerializeObject(items);
File.WriteAllText("Assets\\reiksmes.json", data);
with this try I get error System.UnauthorizedAccessException: Access to the path "/Assets
eiksmes.json" is denied.
also tried:
string data = JsonConvert.SerializeObject(items);
StreamWriter writer = new StreamWriter(Assets.Open("reiksmes.json"));
writer.WriteLine(data);
and with this try I get error System.ArgumentException: Stream was not writable.
Summary:
I think I chose bad directory(Assets), I need to save and load data (json format). So where do I need to save them and how(give example)?
You can't save anything to assets. You can just read from it. You have to save the file to a different folder.
var fileName = "reiksmes.json";
string documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); // Documents folder
var path = Path.Combine(documentsPath, fileName);
Console.WriteLine(path);
if (!File.Exists(path))
{
var s = AssetManager.Open(fileName);
// create a write stream
FileStream writeStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
// write to the stream
ReadWriteStream(s, writeStream);
}
I'm trying to read/write some text files from Local Storage:
KnownFolders.DocumentsLibrary
I have a simple text file that is stored in 'Documents' in my OneDrive folder, and I can read that fine. But when I write out another text file it gets created in my local 'Documents' folder for my PC, not the OneDrive folder. Why is that when I'm pointing to the same folder for both reading and writing, it reads from one location, but writes to another? Here is the method:
public static async void MyMethod()
{
var myFolder = KnownFolders.DocumentsLibrary;
Stream myStream = await myFolder.OpenStreamForReadAsync("readFromHere.txt");
string fileContents = "";
using (StreamReader streamReader = new StreamReader(myStream))
fileContents = streamReader.ReadToEnd();
var outputFile = await myFolder.CreateFileAsync("writeToHere.txt", CreationCollisionOption.OpenIfExists);
await FileIO.WriteTextAsync(outputFile, fileContents);
}
I have problem with save xml in local folder.
I use their variable.
SelectFile is properites with name file ( for example goal.xml or goal(1).xml etc.)
StorageFile storageFile = await ApplicationData.Current.LocalFolder.GetFileAsync(SelectFile);
XDocument document = XDocument.Load(storageFile.Path);
XDocument document = XDocument.Load(storageFile.Path);
This document load good, but load document, not save.
var elementStepOne = document.Elements("StepOne").Single();
elementStepOne.Value = "delete content";
document.Save(SelectFile); // in line I try other mean write.
How I save this document? I want edit this document and save.
There are probably many ways to do this. One way is to use a file stream to save the xml:
StorageFile storageFile = await ApplicationData.Current.LocalFolder.GetFileAsync(SelectFile);
XDocument document = XDocument.Load(storageFile.Path);
var elementStepOne = document.Elements("StepOne").Single();
elementStepOne.Value = "delete content";
var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(
SelectFile,
CreationCollisionOption.ReplaceExisting);
using (var writeStream = await file.OpenStreamForWriteAsync())
{
document.Save(writeStream);
}