I want to develop a windows phone based application in which I need to put the number of files in a folder (this folder is already a part of the project) to a list so that at run time I can access those files. If anybody can give me idea of how to do that then it will be great help.
In normal WPF applications we can write code like
DirectoryInfo di = new DirectoryInfo("D:\\Tempo");
FileInfo[] fi = di.GetFiles("*", SearchOption.AllDirectories);
MessageBox.Show(fi.Length.ToString());
But Windows phone inside solution how do I do that?
I can get a single file access by this code
if (Application.GetResourceStream(new Uri("/WindowsPhone;component/Folder/file09.jpg", UriKind.Relative)) != null)
{
MessageBox.Show("Hi");
}
But inside that folder there are many files and I want to put them into list so at run time I can access those images. But the user won't be knowing about that so it should be a C# code, not a XAML code. Any help would be great.
It's pretty easy.
Make sure you add the specific folder to the Solution. Along with any files you want in that folder.
Make sure each file's Properties are set like so:
Build Action: Content
Copy to Output Directory: Do not copy
Make sure the application had loaded before calling
Lets say I had a folder called "Testfiles" and I want to read from it then:
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
ReadAllFilesFromFolder("Testfiles");
}
// TODO: recursion to get subfolders and files (maybe?)
public async void ReadAllFilesFromFolder(string folder_name)
{
var package = Windows.ApplicationModel.Package.Current.InstalledLocation;
var assetsFolder = await package.GetFolderAsync(folder_name);
foreach (var file in await assetsFolder.GetFilesAsync())
{
// TODO: whatever you want to do with file
// string filename = file.Name;
}
}
Related
I am currently trying to build a electron app using Remix. Thanks to this great setup here https://github.com/itsMapleLeaf/remix-electron.
My requirements is as follows.
When the user uploads an asset, I store it inside a folder xyz in the app path. For mac is /Users/xyz/Application Support/app-folder/assets. I need to show these assets as image tags in electron view. But it fails to locate these files as the public folder is set to /build/. I tried using the file:/// protocol with absolute path but that didn't work as well.
The above repo has a config to set the public folder and that works, but then app stops working as it expects to find JS assets in /build/ folder. And I am not able to dynamically set the "publicPath" value in remix.config.js.
The solution I am looking for, is to have two public folders. 1. default /build/ folder and another one from app location. So remix can serve assets from both paths.
Any help is highly appreciated.
Thank you.
You'll need to update the remix-electron source.
In main.ts, you'll see where it gets all the asset files. You can include your other folders here. Note this is done at initialization, so any dynamically added files won't be included later. You'll need to export a function that lets you add to the asset files.
let [assetFiles] = await Promise.all([
collectAssetFiles(publicFolder),
collectAssetFiles(otherPublicFolder), // add additional folders
app.whenReady(),
])
https://github.com/itsMapleLeaf/remix-electron/blob/20352cc20f976bed03ffd20354c2d011e5ebed64/src/main.ts#L55-L58
Another option is to update the serveAsset function. This is called on every request with the path. You can then check your list of public folders for the asset. This will pickup any new files added.
export async function serveAsset(
request: Electron.ProtocolRequest,
files: AssetFile[],
): Promise<Electron.ProtocolResponse | undefined> {
const url = new URL(request.url)
// TODO: try different folders for list of files to check
const file = files.find((file) => file.path === url.pathname)
if (!file) return
return {
data: await file.content(),
mimeType: mime.getType(file.path) ?? undefined,
}
}
https://github.com/itsMapleLeaf/remix-electron/blob/20352cc20f976bed03ffd20354c2d011e5ebed64/src/asset-files.ts#L24-L37
I have a file hosted on the disk along with my website that I want to read .Not sure how do I access the file when I use System.Environment.CurrentDirectory it point to a D drive location .Can someone please tell me how can I get to my file stored at the root of where my site is hosted.
Thanks
There is an environment variable called HOME in your website's environment that will get you part way there.
You can access it using razor syntax or in code (C#). For example, suppose you have a file called data.txt that is at the root of your site with the default document and the rest of your files. You could get it's full path like this.
#{ var dataFileName = Environment.GetEnvironmentVariable("HOME").ToString() + "\\site\\wwwroot\\data.txt"; }
You can find this out on your own using the Site Control Management/"Kudu". For example, if your website is contoso.azurewebsites.net, then simply navigate to contoso.scm.azurewebsites.net. In here you can learn all about the file system and environment variables available to your website.
For testability, I use below code.
string path = "";
if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("HOME")))
path = Environment.GetEnvironmentVariable("HOME") + "\\site\\wwwroot\\bin";
else
path = ".";
path += "\\Resources\\myfile.json";
In above example, I added myfile.json file to Resources folder in a project with Content and Copy if newer property setting.
This works for me in both localhost and azure:
Path.Combine(System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath, "file_at_root.txt");
System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath is the full local path to your site's root.
I'm currently using AppDomain.CurrentDomain.BaseDirectory (.NET Core project). It returns "D:\home\site\wwwroot\" in Azure and the application root in local so the only difference is adding "bin\\" when it is Azure. I am searching the entire directory tree, just in case, but it can be trimmed.
It's something like:
private static string GetDriverPath(ILogger logger, string fileName)
{
var path = AppDomain.CurrentDomain.BaseDirectory;
if (File.Exists(Path.Combine(path, fileName)))
{
return path;
}
string[] paths= Directory.GetFiles(path, fileName, SearchOption.AllDirectories);
if (paths.Any())
{
return Path.GetDirectoryName(paths.First());
}
throw new FileNotFoundException($"{fileName} was not found in {path}.", fileName);
}
I'm new answering questions and this is an old one but I hope it helps someone.
You can do it using the below code.
string fullFilePath = Environment.GetEnvironmentVariable("HOME") != null
? Environment.GetEnvironmentVariable("HOME") + #"\site\wwwroot\test.txt" //It will give the file directory path post azure deployment
: Path.GetDirectoryName(Path.GetDirectoryName(Directory.GetCurrentDirectory())) + #"\test.txt";//It will give the file directory path in dev environment.
I am trying to create a folder and a image in j2me via code. I am able to creat a image file in Emulator, but when I tried to run that code in mobile(Nokia 2700)...it is giving exception. My code is as folloes.....
Enumeration e = FileSystemRegistry.listRoots();
String root = null;
while (e.hasMoreElements()) {
root = (String) e.nextElement();
break;
}
String newFilePath = "file:///"+root+fileName[i];
FileConnection fileConnection = (FileConnection) Connector.open(newFilePath,
Connector.READ_WRITE);
if(!fileConnection.exists())
fileConnection.create();
else if(fileConnection.fileSize() == mediaSize){
fileConnection.close();
continue;
}
What should I do for creat a image file in previously exist folder, or if possible, how could I creat a folder in j2me.
Some phones only allow creation of folders and files in certain subfolder(s) of root. You may not be allowed to create a folder or file in root on the Nokia 2700.
Typically, you have to go to the "Other" folder on these phones. So try one of these two for path and filename:
file:///c:/other/myfolder/myimage.jpg
file:///e:/other/myfolder/myimage.jpg
Depending on whether you want to save to the phone memory (drive c) or a memory card (drive e).
Question: Why do I get this error while scanning a users 'My Documents' folder, but not when I scan the 'My Music/My Pictures/My Videos' directory?
Secondary, less important question: Is there a way to avoid this without having to specifically filter these folders out, or using a try/catch block?
I prefer answers that teach me how to fish, instead of just giving me fish. Just at this point I am not sure where I need to look to specifically answer this question. I've read through documents about elevating permissions and iterating through the file system, and spent a good week looking for why I can set DirectoryInfo on 'User\My Music' but not 'User\Documents\My Music'(link) and just would enjoy a little boost in a different direction in regards to learning more.
I catch the initial 'UnauthorizedAccessException' that is thrown initially when attempting Directory.GetFiles('path', "*", SearchOption.AllDirectories) where path is the users 'My Documents'. To handle the exception I know that I need to walk the directory manually. Which works, returning the files from the sub-directories.
The code for the initial GetFiles function:
public static string[] GetFiles(string path)
{
string[] files;
try
{
files = Directory.GetFiles(path, "*", SearchOption.AllDirectories);
}
catch(UnauthorizedAccessException ex)
{ files = WalkDirectory(path); }
return files;
}
public static string[] WalkDirectory(string path)
{
List<string> files = new List<string>();
DirectoryInfo dir = new DirectoryInfo(path);
foreach (DirectoryInfo subDir in dir.GetDirectories())
{
try
{
files.AddRange(WalkDirectory(subDir.FullName));
}
catch(UnauthorizedAccessException ex)
{
// complete fail to walk directory listed
throw ex;
}
}
foreach (FileInfo file in dir.GetFiles())
{
files.Add(file.FullName);
}
}
This works out perfectly, until the code attempts to walk the hidden folders: My Music, My Pictures, or My Videos. No matter how I try and re-code to walk the hidden files, I keep receiving the UnauthorizedAccessException.
I understand completely that I am going to code around this. Mainly what I am curious to know, is why is the exception happening under a users folder?
An asssumption I am making is that the folder is a symlink to another directory, because I can make the path ?:\users directory\user\My (Music, Pictures, or Videos) and the code walks those directories then without any issues. This only happens when trying to scan the directory files after setting them from within the users My Documents.
OS: Windows 7
User Privliages: Administrator
Application Elevated to run as administrator
I was speaking about this with a friend, who is not technical, but knows enough tech to hold a conversation and he helped me narrow this question down further. This is actually a duplicate question and was answered at Check if a file is real or a symbolic link.
The folder is a symbolic link that was placed there for backwards compatibility purposes according to this article on TechRepublic: Answers to some common questions about symbolic links under the section Windows Vista and Windows 7 have built-in symbolic links paragraph 2.
In order to specifically avoid attempting to scan this directory without a Try/Catch block on an UnauthorizedAccessException the folder attributes need to be checked to determine if the folder or file in question is a symbolic link. Which again was answered in the above listed stackoverflow question.
I have some client side code that uploads an Outlook email to a document library and as long as the path is pointing to the root of the doc library it works just fine.
#"https://<server>/sites/<subweb>/<customer>/<teamweb>/<Documents>/" + docname;
is the projectUrl in this function :
public bool SaveMail(string filepath, string projectUrl)
{
try
{
using (WebClient webclient = new WebClient())
{
webclient.UseDefaultCredentials = true;
webclient.UploadFile(projectUrl, "PUT", filepath);
}
}
catch(Exception ex)
{
//TO DO Write the exception to the log file
return false;
}
return true;
}
but I have not been able to figur out how to upload to an existing folder i.e. "Emails" in the same document library.
Not even Google seems to know the answer :-)
Note: I know that I could use something like the Copy web service within SharePoint to move the file to its final destination, but that is more like a workaround.
When will I learn not to work that late into the night :-(
Sorry about that question. Igalse is right, I just needed to add "emails/" to the URL. I could swear that I had tried that, but then again it sure looks like I didn't.
With your code I just added /Emails/ to the projectUrl and the upload worked just fine. Have you tried that? Maybe you have permission problem.