DeleteAsync() broke my app - windows

I've been playing around with DeleteAsync() to try and delete a folder called 'Images' inside Assets. I then want to recreate the folder so that it now contains no files.
My folder never deleted, its still in Assets with all its files, but when I re-run the app after the code below it crashes at StorageFolder appFolder = await StorageFolder.GetFolderFromPathAsync(path1);
My guess is that I misunderstood DeleteAsync() and removed some form of reference to the path without actually deleting the folder.
If I delete the 'Images' folder in the VS2015 Solution Explorer, then recreate it manually and add back in all the files manually, the app will run fine again.
Could someone help explain whats going on and if its possible to physically delete a known folder?
//Get the folder location.
string root = Windows.ApplicationModel.Package.Current.InstalledLocation.Path;
string path1 = root + #"\Assets";
string path2 = path1 + #"\Images";
StorageFolder appFolder = await StorageFolder.GetFolderFromPathAsync(path1);
StorageFolder appFolder1 = await StorageFolder.GetFolderFromPathAsync(path2);
//Delete a folder.
if (await appFolder.TryGetItemAsync(#"\Images") != null)
{
await appFolder1.DeleteAsync();
await appFolder.CreateFolderAsync("Images");
}

Related

NativeScript: How to copy a file from an apps folder to a user accessible folder?

I want to copy storage.db to documents or downloads folder. It's very easy to get the file path:
const filePath = application.android.context.getDatabasePath("storage.db").getAbsolutePath();
But, what isn't that easy is to copy that file to a folder users have access to. I searched this whole forum, and I found nothing useful for my case.
I'm using NativeScript 4.0.1 with vanilla JS.
If you want to share the DB file, the easiest way is to use nativescript-share-file plugin, send the file path and it will give you a nice dialog with intent picker, user may choose to Email the file Or save it to local folder etc.,
const shareFile = new ShareFile();
shareFile.open({
path: filePath,
});
I finally found the solution. I've seen so many users trying to achieve this, and I hope this will help all of you.
Add this to your AndroidManifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Install nativescript-permissions:
npm i nativescript-permissions
Asking for permission:
const permissions = require('nativescript-permissions');
permissions.requestPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE, "");
Require the necessary modules:
const fileSystemModule = require("tns-core-modules/file-system");
const application = require("application");
Then, create this function where you need to use it:
function copyFile() {
var myInput = new java.io.FileInputStream(appModule.android.context.getDatabasePath("storage.db").getAbsolutePath());
var myOutput = new java.io.FileOutputStream("/storage/emulated/0/databases/storage.db");
try {
var buffer = java.lang.reflect.Array.newInstance(java.lang.Byte.class.getField("TYPE").get(null), 1024);
var length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
}
catch (err) {
console.info("Error", err);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
exports.copyFile = copyFile;
In my case, the file storage.db will be copied to /storage/emulated/0/databases. If you need to create a folder, just do the following:
try {
var javaFile = new java.io.File("/storage/emulated/0/newfolder");
if (!javaFile.exists()) {
javaFile.mkdirs();
javaFile.setReadable(true);
javaFile.setWritable(true);
}
}
catch (err) {
console.info("Error", err);
}
If the destination folder has a file with the same name as the one you want to copy, you need to remove it first. That's why you should create a specific folder to guarantee it's empty.

How to save images from assets to the internal storage in flutter?

I am trying to save the image from assets to internal storage. But, I could not load the image from assets to file. Here is what I have done:
onTap: () async {
final String documentPath = (await getApplicationDocumentsDirectory()).path;
String imgPath = (galleryItems[currentIndex].assetName).substring(7);
File image = await getImageFileFromAssets(imgPath);
print(image.path);
}
I used substring(7) to eliminate assets/ as, my assetName comes as assets/images/foo.jpg.
Future<File> getImageFileFromAssets(String path) async {
final byteData = await rootBundle.load('assets/$path');
final file =
await File('${(await getApplicationDocumentsDirectory()).path}/$path')
.create(recursive: true);
await file.writeAsBytes(byteData.buffer
.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes));
return file;
}
After I get image, I don't know how to proceed forward to create a directory with my name in internal storage. And, copy file there.
*Note:- I have editted the post, as some basic mistakes were pointed out.
Update
Here is what I came up with. And it saves image in the /storage/emulated/0/Android/data/com.example.my_project/files/Pics/foo.jpg path.
File image = await getImageFileFromAssets(imgPath);
final extDir = await getExternalStorageDirectory();
// Path of file
final myImagePath = '${extDir.path}/Pics';
// Create directory inside where file will be saved
await new Directory(myImagePath).create();
// File copied to ext directory.
File newImage =
await image.copy("$myImagePath/${basename(imgPath)}");
print(newImage.path);
Here are some links that really helped me:
Flutter How to save Image file to new folder in gallery?
How to Save Image File in Flutter ? File selected using Image_picker plugin
How to convert asset image to File?
Special thanks to #David for the help. Please see comments to understand full scene if you are here to solve your similar problem.
So, I am accepting the answer from #David.
You are trying to create a file object in a path that doesn't exist. You're using your asset path, the path relative to the root of your Flutter project. However, this path doesn't exist in the device's documents folder, so the file can't be created there. The file also doesn't exist in the assets folder because you're prepending the documents path.
To fix your issue, you should pass assetName to rootBundle.load(), without the documents path and open the File() somewhere like $documentPath/foo.jpg
Edit:
To create the file you still have to call File.create, so you need to run:
final file = await File('$documentPath/images/foo.jpg').create(recursive: true);
For future reference, this is just to update the solution of #Biplove which really helped me a lot as a newbie...
Future<File> getImageFileFromAssets(String unique, String filename) async {
ByteData byteData = await rootBundle.load(assets/filename));
// this creates the file image
File file = await File('$imagesAppDirectory/$filename').create(recursive: true);
// copies data byte by byte
await file.writeAsBytes(byteData.buffer.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes));
return file;
}
Thanks.

Unexpected response from NSFileManager in Sketch Plugin

I published a Sketch Plugin with some functionalities with a strong dependency in files management.
When execute, plugin needs to check if a folder exists, if not, create, and then manage several files inside this directory.
Some weeks ago, one user reported plugin was crashing in a new Sketch version.
Unexpected response from:
fileExistsAtPath return -folder does not exist- when actually exists in that path
createDirectoryAtPath return 'error' when trying to create a non-existing folder (I've tested both when folder exists and not)
Quick example:
Request
var document = context.document
var documentName = document.displayName()
var documentFolderPath = decodeURIComponent(document.fileURL()).replace('file:///','').replace(documentName,"")
print(documentName)
print(documentFolderPath)
var translationsFolderName = documentName.replace('.sketch','_translations')
var translationsFolderPath = documentFolderPath+translationsFolderName+'/'
print(translationsFolderName)
print(translationsFolderPath)
var fileManager = [NSFileManager defaultManager];
if(![fileManager fileExistsAtPath:translationsFolderPath isDirectory:'YES'])
{
print(translationsFolderPath+" folder does not exist")
if(![fileManager createDirectoryAtPath:translationsFolderPath withIntermediateDirectories:'YES' attributes:nil error:nil])
{
print(translationsFolderPath+" folder can't be created")
}
}
Response
test.sketch
Users/myuser/Documents/
test_translations
Users/myuser/Documents/test_translations/
Users/myuser/Documents/test_translations/ folder does not exist
Users/myuser/Documents/test_translations/ folder can't be created
Script executed in 0.034733s
Any idea?
Thanks!
Your file path is not rooted (doesn't start with /)

Load png files in XNA

I am trying to load all png files from smoe directory( named "bee") but getting an exception that dir. does not exist.
Also, i am sharing the code.
Plese help where i am doing mistake
private List<string> LoadFiles(string contentFolder)
{
DirectoryInfo dir = new DirectoryInfo(this.Content.RootDirectory + "\\" + contentFolder);
if (!dir.Exists)
throw new DirectoryNotFoundException();
List<string> result = new List<string>();
//Load all files that matches the file filter
FileInfo[] files = dir.GetFiles("*.png");
foreach (FileInfo file in files)
{
result.Add(file.Name);
}
return result;
}
Backslashes need to be escaped. e.g. "C:\\path\\to\\some\\directroy\\"
Use Path.Combine to build paths
if you have not selected "Copy to output" in your assets, you won't find that ".png" in that folder.
if your game path is "c:\game\source" and your content project path is "c:\game\content", the content folder you are trying to open, will be "c:\game\source\bin\x86\Debug" and there should be only .xnb files.

Custom Event Receiver - Copy To Folder

I am in the process of writing a custom event receiver. The basic flow is as follows:
Document is added to Library
Based on metadata of document, we check to see if a folder within another document library exists.
If the folder does not exist, it is created.
The newly added document is copied to the folder residing in another document library.
I have got myself to the point, where I can copy newly added files, from one document library to another when they are added. However I cannot figure out how to copy to a specific directory (by name) within a document library. Any help would be greatly received.
Here is my code so far:
SPFile sourceFile = properties.ListItem.File;
SPFile destFile; // Copy file from source library to destination
using (Stream stream = sourceFile.OpenBinaryStream())
{
var destLib = (SPDocumentLibrary) properties.ListItem.Web.Lists[listName];
destFile = destLib.RootFolder.Files.Add(sourceFile.Name, stream);
stream.Close();
}
// Update item properties
SPListItem destItem = destFile.Item;
SPListItem sourceItem = sourceFile.Item;
// Copy meta data
destItem["Title"] = sourceItem["Title"];
//...
//... destItem["FieldX"] = sourceItem["FieldX"];
//...
destItem.UpdateOverwriteVersion();
Answer
//Ensure folder here
var destFolder = destLib.RootFolder.SubFolders["name"];
destFile = destFolder.Files.Add(sourceFile.Name, stream);

Resources