This is how i read my textfile in android.
#if UNITY_ANDROID
string full_path = string.Format("{0}/{1}",Application.streamingAssetsPath, path_with_extention_under_streaming_assets_folder);
// Android only use WWW to read file
WWW reader = new WWW(full_path);
while (!reader.isDone){}
json = reader.text;
// PK Debug 2017.12.11
Debug.Log(json);
#endif
and this is how i read my textfile from pc.
#if UNITY_STANDALONE
string full_path = string.Format("{0}/{1}", Application.streamingAssetsPath, path_with_extention_under_streaming_assets_folder);
StreamReader reader = new StreamReader(full_path);
json = reader.ReadToEnd().Trim();
reader.Close();
#endif
Now my problem is that i don't know how to write the file on mobile cause i do it like this on the standalone
#if UNITY_STANDALONE
StreamWriter writer = new StreamWriter(path, false);
writer.WriteLine(json);
writer.Close();
#endif
Help anyone
UPDATED QUESTION
This is the json file that it is in my streamingasset folder that i need to get
Now my problem is that i don't know how to write the file on mobile
cause I do it like this on the standalone
You can't save to this location. Application.streamingAssetsPath is read-only. It doesn't matter if it works on the Editor or not. It is read only and cannot be used to load data.
Reading data from the StreamingAssets:
IEnumerator loadStreamingAsset(string fileName)
{
string filePath = System.IO.Path.Combine(Application.streamingAssetsPath, fileName);
string result;
if (filePath.Contains("://") || filePath.Contains(":///"))
{
WWW www = new WWW(filePath);
yield return www;
result = www.text;
}
else
{
result = System.IO.File.ReadAllText(filePath);
}
Debug.Log("Loaded file: " + result);
}
Usage:
Let's load your "datacenter.json" file from your screenshot:
void Start()
{
StartCoroutine(loadStreamingAsset("datacenter.json"));
}
Saving Data:
The path to save a data that works on all platform is Application.persistentDataPath. Make sure to create a folder inside that path before saving data to it. The StreamReader in your question can be used to read or write to this path.
Saving to the Application.persistentDataPath path:
Use File.WriteAllBytes
Reading from the Application.persistentDataPath path
Use File.ReadAllBytes.
See this post for a complete example of how to save data in Unity.
This is the way I do it without the WWW class (works for Android an iOS), hope its useful
public void WriteDataToFile(string jsonString)
{
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
if (!File.Exists(filePath))
{
File.Create(filePath).Close();
File.WriteAllText(filePath, jsonString);
}
else
{
File.WriteAllText(filePath, jsonString);
}
}
Related
i am using selenium or webBrowser to navigate the web url. the weburl downloaded the txt file. instead of downloading a file i want the file data in a variable. Can anybody please help in this.
for eq url is "https://trends.google.com/trends/api/explore?hl=en-US&tz=-330&req=%7B%22comparisonItem%22:%5B%7B%22keyword%22:%22tsla%22,%22geo%22:%22US%22,%22time%22:%22today+1-m%22%7D,%7B%22keyword%22:%22bitcoin%22,%22geo%22:%22US%22,%22time%22:%22today+1-m%22%7D%5D,%22category%22:0,%22property%22:%22%22%7D&tz=-330"
code snippet :
tcs = new TaskCompletionSource<bool>();
wb.DocumentCompleted += documentCompletedHandler;
try
{
wb.Navigate(url.ToString());
// await for DocumentCompleted
await tcs.Task; ----> here adownloaded a file but i want the file data;
}
finally
{
wb.DocumentCompleted -= documentCompletedHandler;
}
Where do I find the location of the folders and text files I created in windows phone 8. Can we see it in the explorer like we search for the app data in Windows 8? I'm not using IsolatedStorage, instead Windows.Storage. I want to check if the folders and files are created as I want.
This is how I write the file
IStorageFolder dataFolder = await m_localfolder.CreateFolderAsync(App.ALL_PAGE_FOLDER, CreationCollisionOption.OpenIfExists);
StorageFile PageConfig = null;
try
{
PageConfig = await dataFolder.CreateFileAsync("PageConfig.txt", CreationCollisionOption.OpenIfExists);
}
catch (FileNotFoundException)
{
return false;
}
EDIT
try
{
if (PageConfig != null)
{
using (var stream = await PageConfig.OpenStreamForWriteAsync())
{
DataWriter writer = new DataWriter(stream.AsOutputStream());
writer.WriteString(jsonString);
}
}
}
catch (Exception e)
{
string txt = e.Message;
return false;
}
And this is how I read the file from the folder
try
{
var dataFolder = await m_localfolder.GetFolderAsync(App.ALL_PAGE_FOLDER);
var retpng = await dataFolder.OpenStreamForReadAsync("PageConfig.txt");
if (retpng != null)
{
try
{
using (StreamReader streamReader = new StreamReader(retpng))
{
jsonString = streamReader.ReadToEnd();
}
return jsonString;
}
catch (Exception)
{
}
}
}
catch (FileNotFoundException)
{
}
There are also other folders created. I dont receive any exceptions while writing but when I read the string is empty.
Windows.Storage.ApplicationData.LocalFolder(MSDN link here) is another name for Isolated Storage that is in Windows.Storage namespace. The only other location you can access is your app's install directory (and only read-only).
You can use Windows Phone Power Tools to browse what files are in your app's Isolated Storage, or the command line tool that comes with the SDK.
With the help of Windows Phone Power tools, I figured out that there was no text being written in file.
So I converted string to byte and then wrote it to the file and it works! Don't know why the other one does not work though..
using (var stream = await PageConfig.OpenStreamForWriteAsync())
{
byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(jsonString);
stream.Write(fileBytes, 0, fileBytes.Length);
}
The command line tool that comes with Windows Phone SDK 8.0 is Isolated Storage Explorer (ISETool.exe) which reside in "Program Files (x86)\Microsoft SDKs\Windows Phone\v8.0\Tools\IsolatedStorageExplorerTool" folder for default installation
ISETool.exe is used to view and manage the contents of the local folder
I am not able to use DownloadDataAsync method.The only option present is DownloadStringAsync method.How can I download a zip file using this method.(I am new to windows phone 8 app development)
I just thought to share the solution that worked for me.
I created a web request to the url given and downloaded the gzip file into isolated storage file.Now after downloading i created a destination file stream and stored the compressed gzip stream file from source file to destination file using WriteByte method of GZipStream.Now we get uncompressed file.
Note:-GZipStream can be added to Visual studio from NuGet manager.
Here is the code snippet which i used to download and extract GZip file.
public async Task DownloadZipFile(Uri fileAdress, string fileName)
{
try
{
WebRequest request = WebRequest.Create(fileAdress);
if (request != null)
{
WebResponse webResponse = await request.GetResponseAsync();
if (webResponse.ContentLength != 0)
{
using (Stream response = webResponse.GetResponseStream())
{
if (response.Length != 0)
{
using (IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isolatedStorage.FileExists(fileName))
isolatedStorage.DeleteFile(fileName);
using (IsolatedStorageFileStream file = isolatedStorage.CreateFile(fileName))
{
const int BUFFER_SIZE = 100 * 1024;
byte[] buf = new byte[BUFFER_SIZE];
int bytesread;
while ((bytesread = await response.ReadAsync(buf, 0, BUFFER_SIZE)) > 0)
{
file.Write(buf, 0, bytesread);
}
file.Close();
FileStream sourceFileStream = File.OpenRead(file.Name);
FileStream destFileStream = File.Create(AppResources.OpenZipFileName);
GZipStream decompressingStream = new GZipStream(sourceFileStream, CompressionMode.Decompress);
int byteRead;
while ((byteRead = decompressingStream.ReadByte()) != -1)
{
destFileStream.WriteByte((byte)byteRead);
}
decompressingStream.Close();
sourceFileStream.Close();
destFileStream.Close();
PhoneApplicationService.Current.State["DestinationFilePath"] = destFileStream.Name;
}
}
FileDownload = true;
}
}
}
}
if (FileDownload == true)
{
return DownloadStatus.Ok;
}
else
{
return DownloadStatus.Other;
}
}
catch (Exception exc)
{
return DownloadStatus.Other;
}
}
Do you must use DownloadStrringAsync method? otherwise you can check these:
How to extract zipped file received from HttpWebResponse?
download and decompress a zip file in windows phone 8 application
Extract zip file from isolatedstorage
How to download a GZIP file from web to Windows Phone 7 and unzip the contents
To download zip file from the url first there is need to store zip files into isolated storage and after that extract it and read the file as per requirement.
http://axilis.hr/uznip-archives-windows-phone
I was just curious, is it possible to have direct network transfers in c#, without local caching.
e.g.
I have response stream which represents GoogleDrive file and request stream to upload file to another GoogleDrive account.
At that momment I can download file to local pc and next upload it to the google drive. But is it possible to upload it directly from one google drive to another or, at least, start uploading before full download will be completed.
Thank
Yes you can, with Google Drive api you download file into a stream and you keep it in memory so you can upload it to another google drive account after login.
You get your token on first account and download a file keeping it in a stream.
THen you authenticate on other google drive account and upload the file using the stream.
PS: When you are inserting the file on the second drive account, instead of getting
the byte[] array reading the file from disk you get the byte array from the stream you have in memory.
File Download Example:
public static System.IO.Stream DownloadFile(
IAuthenticator authenticator, File file) {
if (!String.IsNullOrEmpty(file.DownloadUrl)) {
try {
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
new Uri(file.DownloadUrl));
authenticator.ApplyAuthenticationToRequest(request);
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK) {
return response.GetResponseStream();
} else {
Console.WriteLine(
"An error occurred: " + response.StatusDescription);
return null;
}
} catch (Exception e) {
Console.WriteLine("An error occurred: " + e.Message);
return null;
}
} else {
// The file doesn't have any content stored on Drive.
return null;
}
File insert example:
private static File insertFile(DriveService service, String title, String description, String parentId, String mimeType, String filename) {
// File's metadata.
File body = new File();
body.Title = title;
body.Description = description;
body.MimeType = mimeType;
// Set the parent folder.
if (!String.IsNullOrEmpty(parentId)) {
body.Parents = new List<ParentReference>()
{new ParentReference() {Id = parentId}};
}
// File's content.
byte[] byteArray = System.IO.File.ReadAllBytes(filename);
MemoryStream stream = new MemoryStream(byteArray);
try {
FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, mimeType);
request.Upload();
File file = request.ResponseBody;
// Uncomment the following line to print the File ID.
// Console.WriteLine("File ID: " + file.Id);
return file;
} catch (Exception e) {
Console.WriteLine("An error occurred: " + e.Message);
return null;
}
}
I try to figure out how I could read and write a large text file in WinRT line by line.
FileIO.ReadLinesAsync respectively FileIO.WriteLinesAsync would not work because they work with a list of strings that is passed respectively returned. With large text files that may cause an OutOfMemoryException.
I could of course write line by line using FileIO.AppendTextAsync but that would be inefficient.
What I figured out was that I could use a StreamReader or StreamWriter like in the sample code below.
But is there really no native Windows Runtime way to achieve this?
I know by the way that Windows Store Apps are not supposed to read or write large text files. I need a solution just because I am writing a recipe book for programmers.
Sample: Reading using a StreamReader:
StorageFile file = ...
await Task.Run(async () =>
{
using (IRandomAccessStream winRtStream = await file.OpenAsync(FileAccessMode.Read))
{
Stream dotnetStream = winRtStream.AsStreamForRead();
using (StreamReader streamReader = new StreamReader(dotnetStream))
{
string line;
while ((line = streamReader.ReadLine()) != null)
{
...
}
}
}
});
Actually, your assumpltion about list of string is not completelly correct. FileIO.WriteLinesAsync accepts IEnumerable<string> as a parameter. So you can just do somethig like this:
IEnumerable<string> GenerateLines()
{
for (int ix = 0; ix < 10000000; ix++)
yield return "This is a line #" + ix;
}
//....
WriteLinesAsync(file, GenerateLines());
As for reading of a big file, you are right, we need some custom work like you did in your sample.
Here is my solution for writing large files using a StreamWriter. The used memory stays low even when writing very large files:
StorageFile file = ...
using (var randomAccessStream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
using (var outputStream = randomAccessStream.GetOutputStreamAt(0))
{
using (StreamWriter streamWriter =
new StreamWriter(outputStream.AsStreamForWrite()))
{
for (...)
{
await streamWriter.WriteLineAsync(...);
}
}
}
}