I need to know how to check for the endings of all the files in the Assets folder.
Its for creating a list of saved files.
public static void Load()
{
if (File.Exists(Application.dataPath + "/data1.sav"))
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.dataPath + "/data1.sav", FileMode.Open);
SaveLoad.savedData = (List<saveData>)bf.Deserialize(file);
file.Close();
}
}
^this load function works fine.
Now i need something like this:
(pseudocode)
if (File.Exists(With the ending: ".sav") ????
{
Create a list of all those files in a String Array!
}
so if i would have in the Assets folder:
"data1.sav"
"data2.sav"
"test.sav" it should return a String Array with the
size of 3 and which include ["data1.sav"], ["data2.sav"] and ["test.sav"]
Just use GetFiles()
Code would be something like:
string[] files = Directory.GetFiles(DirectoryPath, "*.sav");
Related
I have a bunch of xml files in assets folder, I add path to pubspec.yaml and path looks like this 'assets/data/somename.xml' I need to get data from them and this is the way how i got it now
List filePathList = ['assets/data/widow.xml','assets/data/door.xml'];
for(int i = 0;i<filePathList.length;i++){
var xmlFile = XmlDocument.parse(await rootBundle.loadString(filePathList[i]));
checkListtemplateXmlList.add(xmlFile);
}
How you can see i use realy bad way to take data from files,
there will be many more xml files in the future so i need some solution to this problem to not add path in filePathList for every file in assets folder.
Also i made a loadData function that load all files like i want, but my json files are in directory that i got with using getApplicationDocumentDirectory class. There is a code
static Future<void> loadData() async {
final dir = await getApplicationDocumentsDirectory();
List<FileSystemEntity> files = await dir.list().toList();
for (int i = 0; i < files.length; i++) {
String filepath = files[i].path;
File newFile = File(filepath);
String name = p.basenameWithoutExtension(newFile.path);
String myExtension = p.extension(filepath);
if(myExtension != '.json'){
} else{
checkLists.add(CheckList(name));
}
}
for(int i = 0;i< checkLists.length;i++){
await checkLists[i].readFile();
}
}
how i can do something like this in my getXmlData function
Inside the pubspec define only the folder:
assets:
- assets/data/
This will "load" all files inside the data folder.
And using this code:
// This will give a list of all files inside the `assets`.
var assets = await rootBundle.loadString('AssetManifest.json');
And use a filter to get all xml files.
Map json = json.decode(assets);
List get = json.keys.where((element) => element.endsWith(".xml")).toList();
In my game, you can take screenshots of the world, which are saved in Application.persistentDataPath. I want to make a gallery where you can then see all these screenshots. Because you need to write to the file, I can't use Resources folder or Application.streamingAssetsPath. I could read the files one sprite at a time, using the name, but that's not really practical. So how could I load all files and add them to an array or list? I basically need the equivalent of Resources.LoadAll(). Does anyone know how to achieve this?
You can use Directory.GetFiles(string,string) to return all filepaths in the persistentData folder e.g. by file extension ("*.jpg")
Then you can use e.g. UnityWebRequestTexture.GetTexture also on local file paths and load assets from the persistent data path like
public Dictionary<string, Texture2D> textures = new Dictionary<string, Texture2D>();
private void Start()
{
var fileNames = Directory.GetFiles(Application.persistentDataPath, "*.jpg");
foreach(var fileName in fileNames)
{
StartCoroutine (LoadFile(fileName));
}
}
private IEnumerator LoadFile(string filePath)
{
using (UnityWebRequest uwr = UnityWebRequestTexture.GetTexture(filePath))
{
yield return uwr.SendWebRequest();
if (uwr.isNetworkError || uwr.isHttpError)
{
Debug.Log(uwr.error);
}
else
{
// Get downloaded asset bundle
var texture = DownloadHandlerTexture.GetContent(uwr);
// Something with the texture e.g.
// store it to later access it by fileName
var fileName = Path.GetFileName(filePath);
textures[fileName] = texture;
}
}
}
I'm trying to merge all my text files into one file.
The problem I am having is that the file names are based on data previously captured in my app. I don't know how to define my path to where the text files are, maybe. I keep getting a error, but the path to the files are correct.
What am I missing?
string filesread = System.AppDomain.CurrentDomain.BaseDirectory + #"\data\Customers\" + CustComboB.SelectedItem + #"\";
Directory.GetFiles(filesread);
using (var output = File.Create("allfiles.txt"))
{
foreach (var file in new[] { filesread })
{
using (var input = File.OpenRead(file))
{
input.CopyTo(output);
}
}
}
System.Diagnostics.Process.Start("allfiles.txt");
my error:
System.IO.DirectoryNotFoundException
HResult=0x80070003
Message=Could not find a part of the path 'C:\Users\simeo\source\repos\UpMarker\UpMarker\bin\Debug\data\Customers\13Dec2018\'.
I cant post a pic, but let me try and give some more details on my form.
I select a combobox item, this item is a directory. then I have a listbox that displays the files in my directory. I then have a button that executes my desires of combining the files. thanks
I finally got it working.
string path = #"data\Customers\" + CustComboB.SelectedItem;
string topath = #"data\Customers\";
string files = "*.txt";
string[] txtFiles;
txtFiles = Directory.GetFiles(path, files);
using (StreamWriter writer = new StreamWriter(topath + #"\allfiles.txt"))
{
for (int i = 0; i < txtFiles.Length; i++)
{
using (StreamReader reader = File.OpenText(txtFiles[i]))
{
writer.Write(reader.ReadToEnd());
}
}
System.Diagnostics.Process.Start(topath + #"\allfiles.txt");
}
I need to download an image with GS and save it in a specific drive folder.
I'm able to save the image in the root folder but i cannot save it in a specific folder:
function downloadFile(fileURL,folder) {
var fileName = "";
var fileSize = 0;
var response = UrlFetchApp.fetch(fileURL, {muteHttpExceptions: true});
var rc = response.getResponseCode();
if (rc == 200) {
var fileBlob = response.getBlob()
var folder = DriveApp.getFoldersByName(folder);
if (folder != null) {
var file = DriveApp.createFile(fileBlob);
fileName = file.getName();
fileSize = file.getSize();
}
}
var fileInfo = { "rc":rc, "fileName":fileName, "fileSize":fileSize };
return fileInfo;
}
Question: what have I to add to use the variable "folder"?
I found a lot of examples with "DocList" Class that is not in use anymore
Many thanks
Well, I guess GAS has make a lot of progress on developing its API, the function
createFile(blob) of an object Folder will do the job:
https://developers.google.com/apps-script/reference/drive/folder#createfileblob
// Create an image file in Google Drive using the Maps service.
var blob = Maps.newStaticMap().setCenter('76 9th Avenue, New York NY').getBlob();
DriveApp.getRootFolder().createFile(blob);
It's quite late for the answer but just incase some one runs into the situation.
Are you familiar with this app? It does exactly what you're asking for.
However, if you want to re-create this for your own purposes, I would change your declaration of variable file to read as such:
var file = folder.next().createFile(fileBlob);
when you create your variable folder, the method you use creates a FolderIterator, not a single folder. You have to call the next() method to get a Folder object.
To be precise with your script and avoid saving to an incorrect-but-similarly-named folder, I would recommend passing the folder ID to your script rather than the folder Name. If you pass the folder ID, you could declare folder as:
var folder = DriveApp.getFolderById(folder);
and then continue the script as you have it written. I hope that helps.
Working on similar problem, I came up with the solution below to save a file to a folder. If the folder doesn't exist it creates it, otherwise it saves the file specified by "FOLDER_NAME"
var folderExists = checkFolderExists("FOLDER_NAME");
if (folderExists) {
saveFolder = DriveApp.getFolderById(folderExists);
} else {
saveFolder = DriveApp.createFolder("FOLDER_NAME");
}
// Make a copy of the file in the root drive.
var file = DriveApp.getFileById(sheetID);
// Take the copy of the file created above and move it into the folder:
var newFile = DriveApp.getFolderById(saveFolder.getId()).addFile(file);
// Remove the copy of the file in the root drive.
var docfile = file.getParents().next().removeFile(file);
Further to Eric's answer, I have also provided a utility function that checks if the folder exists. It's reusable in any project.
function checkFolderExists(fName) {
try {
var folderId;
var folders = DriveApp.getFolders();
while (folders.hasNext()) {
var folder = folders.next();
folderName = folder.getName();
if (folderName == fName) {
folderId = folder.getId();
}
}
} catch(e) {
log("Services::checkFolderExists()" + e.toString());
throw e;
}
return folderId;
}
I have a word template and I want to create doc file from that, also I want to replace add data in place of bookmarks present in the template.
I have been able to create a doc file, but I am not able to understand, how to add data in place of bookmarks?
My code till now:
private void CreateSampleWordDocument()
{
string sourceFile = Path.Combine(Environment.CurrentDirectory, "GeneralWelcomeLetter.dotx");
string destinationFile = Path.Combine(Environment.CurrentDirectory, "Sample.docx");
try
{
File.Copy(sourceFile, destinationFile, true);
WordprocessingDocument document = WordprocessingDocument.Open(destinationFile, true);
document.ChangeDocumentType(DocumentFormat.OpenXml.WordprocessingDocumentType.Document);
MainDocumentPart mainPart = document.MainDocumentPart;
DocumentSettingsPart documentSettingPart1 = mainPart.DocumentSettingsPart;
AttachedTemplate attachedTemplate1 = new AttachedTemplate() { Id = "relationId1" };
documentSettingPart1.Settings.Append(attachedTemplate1);
}
catch
{
}
}
Now to add data from database in place of bookmarks?