Load png files in XNA - windows-phone-7

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.

Related

How to read any CSV file from my pcl folder in xamarin forms

I have one CSV file in my PCL folder, i want to get the path of that file so i can read the files using File.ReadAllLine().
Here is the code I have been used not not getting the file, as i have changed the file to the embedded resources
I want this in string[] lines.
string[] lines = File.ReadAllLines("PrinterTestSample.Csv.UserData.csv");
You will need to get a stream from the assembly where the embedded resource is. Below a sample code on how to read it.
// replace App with a class that is in the project where the embedded resource is.
var assembly = typeof(App).GetTypeInfo().Assembly;
// replace App3 with the namespace where your file is
var stream = assembly.GetManifestResourceStream("App3.XMLFile1.xml");
var lines = new List<string>();
using var reader = new StreamReader(stream);
while (reader.ReadLine() is { } line)
{
lines. Add(line);
}

Script to move files from folder to another folder using paths in text file

On Windows 8, could someone please help me create a script to move some images from a particular folder to another folder?
The file path that lists the images i want to move (not all images) from the folder are listed in this file: C:\Users\Emmanuel\Desktop\test.txt
The folder in which contains some of the images I want removed appear in this folder:
C:\Users\Computer\Desktop\Images1
The folder in which I want the images to be moved to is this folder:
C:\Users\Computer\Desktop\Images2
Your help will be much appreciated
Try this where SourcesFile is your test.txt and DestFolder is the destination.
public int Run()
{
if (!File.Exists(SourcesFile))
{
throw new ArgumentException("Source folder does not exist");
}
if (!Directory.Exists(DestFolder))
{
Console.WriteLine("Destination folder doesn't exist");
Console.WriteLine("Creating destination folder...");
Directory.CreateDirectory(DestFolder);
}
string[] files = File.ReadAllLines(SourcesFile);
Console.WriteLine("Moving {0} files...", files.Length);
foreach (string file in files)
{
string dest = Path.Combine(DestFolder, Path.GetFileName(file));
if (File.Exists(dest))
{
string newFilename = string.Format("{0}_{1}{2}",
Path.GetFileNameWithoutExtension(file),
Guid.NewGuid().ToString("N"),
Path.GetExtension(file));
string newDest = Path.Combine(DestFolder, newFilename);
Console.WriteLine("File {0} already exists, copying file to {1}", file, newDest);
File.Move(file, newDest);
continue;
}
File.Move(file, dest);
}
return 0;
}

NotifyFilter of FileSystemWatcher not working

I have a windows service (and verified the code by creating a similar WinForms application) where the NotifyFilter doesn't work. As soon as I remove that line of code, the service works fine and I can see the event-handler fire in the WinForms application.
All I'm doing is dropping a text file into the input directory for the FileSystemWatcher to kick off the watcher_FileChanged delegate. When I have the _watcher.NotifyFilter = NotifyFilters.CreationTime; in there, it doesn't work. When I pull it out, it works fine.
Can anyone tell me if I'm doing something wrong with this filter?
Here is the FSW code for the OnStart event.
protected override void OnStart(string[] args)
{
_watcher = new FileSystemWatcher(#"C:\Projects\Data\Test1");
_watcher.Created += new FileSystemEventHandler(watcher_FileChanged);
_watcher.NotifyFilter = NotifyFilters.CreationTime;
_watcher.IncludeSubdirectories = false;
_watcher.EnableRaisingEvents = true;
_watcher.Error += new ErrorEventHandler(OnError);
}
private void watcher_FileChanged(object sender, FileSystemEventArgs e)
{
// Folder with new files - one or more files
string folder = #"C:\Projects\Data\Test1";
System.Console.WriteLine(#"C:\Projects\Data\Test1");
//Console.ReadKey(true);
// Folder to delete old files - one or more files
string output = #"C:\Temp\Test1\";
System.Console.WriteLine(#"C:\Temp\Test1\");
//Console.ReadKey(true);
// Create name to call new zip file by date
string outputFilename = Path.Combine(output, string.Format("Archive{0}.zip", DateTime.Now.ToString("MMddyyyy")));
System.Console.WriteLine(outputFilename);
//Console.ReadKey(true);
// Save new files into a zip file
using (ZipFile zip = new ZipFile())
{
// Add all files in directory
foreach (var file in Directory.GetFiles(folder))
{
zip.AddFile(file);
}
// Save to output filename
zip.Save(outputFilename);
}
DirectoryInfo source = new DirectoryInfo(output);
// Get info of each file into the output directory to see whether or not to delete
foreach (FileInfo fi in source.GetFiles())
{
if (fi.CreationTime < DateTime.Now.AddDays(-1))
fi.Delete();
}
}
I've been having trouble with this behavior too. If you step through the code (and if you look at MSDN documenation, you'll find that NotifyFilter starts off with a default value of:
NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.LastWrite
So when you say .NotifyFilter = NotifyFilters.CreationTime, you're wiping out those other values, which explains the difference in behavior. I'm not sure why NotifyFilters.CreationTime is not catching the new file... seems like it should, shouldn't it!
You can probably just use the default value for NotifyFilter if it's working for you. If you want to add NotifyFilters.CreationTime, I'd recommend doing something like this to add the new value and not replace the existing ones:
_watcher.NotifyFilter = _watcher.NotifyFilter | NotifyFilters.CreationTime;
I know this is an old post but File Creation time is not always reliable. I came across a problem where a Log file was being moved to an archive folder and a new file of the same name was created in it's place however the file creation date did not change, in fact the meta data was retained from the previous file (the one that was moved to the archive) .
Windows has this cache on certain attributes of a file, file creation date is included. You can read the article on here: https://support.microsoft.com/en-us/kb/172190.

How to read files from project folders?

When the first time my app starts on a windows phone, I want to get some files(xml/images) from project folders and write them to the isolated storage .
How do I detect that my app is running for the first time?
How do I access file in project folders?
Here is another way to read files from your visual studio project. The following shows how to read a txt file but can be used for other file as well. Here the file is in the same directory as the .xaml.cs file.
var res = App.GetResourceStream(new Uri("test.txt", UriKind.Relative));
var txt = new StreamReader(res.Stream).ReadToEnd();
make sure your file is marked as Content.
If you mean project folders as in the folders in your visual studio project, I usually right click on the files and set the build action to 'Embedded Resource'. At runtime, you can read the data from the embedded resource like so:
// The resource name will correspond to the namespace and path in the file system.
// Have a look at the resources collection in the debugger to figure out the name.
string resourcePath = "assembly namespace" + "path inside project";
Assembly assembly = Assembly.GetExecutingAssembly();
string[] resources = assembly .GetManifestResourceNames();
List<string> files = new List<string>();
if (resource.StartsWith(resourcePath))
{
StreamReader reader = new StreamReader(assembly.GetManifestResourceStream(resource), Encoding.Default);
files.Add(reader.ReadToEnd());
}
To read the images you would need something like this to read the stream:
public static byte[] ReadAllBytes(Stream input)
{
byte[] buffer = new byte[32 * 1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}

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