I have to read the text content from an .txt file, this file is located in app installed folder, in a subfolder, according to Microsoft docs, I am doing it like this:
private async void readMyFile()
{
// Get the app's installation folder.
StorageFolder appFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
// Get a file from a subfolder of the current folder by providing a relative path.
string txtFileName = #"\myfolder\myfile.txt";
try
{
//here my file exists and I get file path
StorageFile txtfile = await appFolder.GetFileAsync(txtFileName);
Debug.WriteLine("ok file found: " + txtfile.Path);
//here I get the error
string text = await FileIO.ReadTextAsync(txtfile);
Debug.WriteLine("Txt is: " + text);
}
catch (FileNotFoundException ex)
{
}
}
the error is:
Exception thrown: 'System.IO.FileNotFoundException' in mscorlib.ni.dll
exception file not found: System.IO.FileNotFoundException: The filename, directory name, or volume label syntax is incorrect. (Exception from HRESULT: 0x8007007B)
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at Smadshop.MainPage.<testExistsFile>d__8.MoveNext()
Have to notice that if I use the file without subfolder everything is working fine.
you can do it in other way, using URI :
using Windows.Storage;
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync("ms-appx:///file.txt");
So in your case it will be:
StorageFile txtfile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///myfolder/myfile.txt"));
I think you need to use:
string txtFileName = #".\myfolder\myfile.txt";
The dot in the filename represents the current folder. In you want to specify using relative paths, then #"\myfolder\myfile.txt" is not correct.
GetFileAsync will take relative path in form folder/fileName. You can also get folder first and than file or use GetItemAsync
StorageFolder appFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
// Get a file from a subfolder of the current folder
// by providing a relative path.
string image = #"Assets\Logo.scale-100.png";
var logoImage = await appFolder.GetFileAsync(image);
#"\myfolder\myfile.txt"; if its a network path should be #"\\myfolder\myfile.txt"; If its a local file it needs a drive letter ie.#"c:\myfolder\myfile.txt";
However the documentation for GetFileAsync shows a file in a subfolder would be #"myfolder\myfile.txt"
When you use a filename without a subfolder it will look in the current folder.
Related
I want to download a folder with its files in various mime type. My virtual path is "http://localhost/attachments/". My sub folders are "certificates/id". So when clicking on a grid i pass id to the download page. But it throws an exception like virtual path is invalid. 'http://localhost/attachments/certificates/id)'.
In below code, Request.Params[0] meant id, this points the endlevel folder which i want to make a zip folder.
Any guidance would be grateful.
using (ZipFile zip = new ZipFile())
{
string VirtualPath = ConfigurationManager.AppSettings.Get("AttachmentsShowVirtualPath");
string Path = string.Empty;
Path = "certificates" + "/";
string folderPath = VirtualPath + Path + Request.Params[0] + "/";
zip.CompressionLevel = CompressionLevel.None;
zip.AddSelectedFiles(".", Server.MapPath(folderPath), "", false);
zip.Save(Response.OutputStream);
}
First, are you using DotNetZip? I have never use it, but try changing the . to *.*
If not getting the file, try to do Directory.GetFiles to check if eveything is pointing correctly and your code has read permission over the directory https://msdn.microsoft.com/en-us/library/07wt70x2%28v=vs.110%29.aspx
Or try to use official Zip class from https://msdn.microsoft.com/en-us/library/system.io.compression.zipfile%28v=vs.110%29.aspx With this method: ZipFile.CreateFromDirectory
I'm making a Windows 10 Universal App and I want the user to pick a folder to save the document files for the App. The path for this folder is saved to ApplicationData.Current.RoamingSettings.Values.
Here's the code:
On first Start:
var folderPicker = new FolderPicker { SuggestedStartLocation = PickerLocationId.ComputerFolder };
StorageFolder folder = await folderPicker.PickSingleFolderAsync();
StorageFolder homeFolder = await folder.CreateFolderAsync("App1 Data", CreationCollisionOption.OpenIfExists);
var save = ApplicationData.Current.RoamingSettings.Values;
save["HomeFolder"] = homeFolder.Path;
When HomeFolder is set:
string dir = save["HomeFolder"].ToString();
try
{
StorageFolder homeFolder = await StorageFolder.GetFolderFromPathAsync(dir);
}
catch (Exception e)
{
Debug.WriteLine(e.ToString());
}
The thrown Exception in the second code sample is:
System.UnauthorizedAccessException: access denied (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
So my question is, how do you use the GetFolderFromPathAsync function correctly?
I checked all strings for the paths, they are all right, even
StorageFolder.GetFolderFromPathAsync(storageFolder.Path);
doesn't work.
Do you know a solution?
Use the StorageFile directly rather than converting to a path.
To store the file returned from the file picker for later use save the StorageFile in the AccessCache classes FutureAccessList or MostRecentlyUsedList. The path doesn't include the spermissions needed to open the file. The StorageFile carries the permissions and grants access to the file.
I discussed this in more detail in my blog entry Skip the path: stick to the StorageFile
I have a code to create new folder and move file to that folder using FileSystemWatcher.But it gives following error.
System.IO.IOException: The process cannot access the file because it
is being us ed by another process. at
System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.__Error.WinIOError() at System.IO.File.Move(String
sourceFileName, String destFileName) at
FolderWatcher.Program.ProcessRenewalFolder(Object sender,
FileSystemEventA rgs e)
Following is the code
'private static void ProcessRenewalFolder(object sender, FileSystemEventArgs e)
{
Console.WriteLine("Renewal Received.... ");
DirectoryInfo d = new DirectoryInfo(#"E:\SCN_DOCS\RENEWAL\");
DirectoryInfo dest = new DirectoryInfo(#"E:\QUEUED_SCN_DOCS\RENEWAL\");
if (!d.Exists)
{
return;
}
FileInfo[] Files = d.GetFiles("*.pdf");
string jobNo = "";
string branchCode = "";
foreach (FileInfo file in Files)
{
jobNo = file.Name;
DirectoryInfo newDir = null;
if (!Directory.Exists(dest.FullName + jobNo.ToUpper()))
{
System.IO.Directory.CreateDirectory(dest.FullName + jobNo.Substring(0, file.Name.LastIndexOf(".")).ToUpper());
}
Console.WriteLine(jobNo + " - " + branchCode);
try
{
File.Move(file.FullName, dest.FullName + jobNo.Substring(0, file.Name.LastIndexOf(".")).ToUpper() + "\\" + file.Name.ToUpper());
UpdateRenewal(jobNo.Substring(0, file.Name.LastIndexOf(".")).ToUpper());
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}'
Please let me know the reason for this...
in below folder path
DirectoryInfo d = new DirectoryInfo(#"E:\SCN_DOCS\RENEWAL\")
any new file created using your c# application if yes than you need to dispose the object of newly created file for example
Bitmap bitmap = new Bitmap();
// your Image file creation code...
bitmap.Dispose();
as per your question you are working with .pdf file so if you created any new pdf file in above folder just before moving file, than you need to dispose that object of newly created pdf file.
see this answer https://stackoverflow.com/a/31830176/4988990
It can happen if the file is still open in the program that generated the PDF (i.e. the program that put it in the folder).
When you work with a directory watcher I suggest that you:
Put all watched files in some sort of a list.
Use a Timer and process files that have been in the list for X seconds.
If the file can't be accessed, put it in the end of the list.
In that way you get a more forgiving solution and it's not likely that you'll miss files due to errors.
I want to rename a file with particular extension present inside a folder. For example C:\Users\Username\Desktop\Convert is the file location I'm in. There be another folder for example "C:\Users\Username\Desktop\Convert\Unknown folder". I wont be knowing the name of this unknown folder. There will be a .txt file inside that unknown folder. So how will I access the unknown folder and change the extension of the .txt file to .jpg ?
This is what i have tried and its not working :
string ourPath = #"C:\Users\username\Desktop\Convert\123.txt";
string newPath = Path.ChangeExtension(ourPath, "jpg");
File.Move(ourPath, newPath);
}
Get all the files in descendant folders using SearchOption.AllDirectories then find your file and do whatever you want:
var files = Diretory.GetFiles(
#"C:\Users\Username\Desktop\Convert",
"*.txt",
SearchOption.AllDirectories);
var filePath = files.FirstOrDefault(f => Path.GetFileName(f) == "123.txt");
if(filePath != null)
{
// manipulate the file ext. etc..
}
I am trying to load a pdf file from a folder in my win8 app. It is in the test folder. I try
StorageFile file = StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Test/example.pdf"));
That gives me a file not found. However, if I change the extension of example.pdf to jpg, then change the code to look for example.jpg, it does work properly. What is going on?
Try this:
public async Task<StorageFile> GetFileAsync(string directory, string fileName)
{
string filePath = BuildPath(directory, fileName);
string directoryName = Path.GetDirectoryName(filePath);
StorageFolder storageFolder = await StorageFolder.GetFolderFromPathAsync(directoryName);
StorageFile storageFile = await storageFolder.GetFileAsync(fileName);
return storageFile;
}
public string BuildPath(string directoryPath, string fileName)
{
string directory = Path.Combine(Package.Current.InstalledLocation.Path, directoryPath);
return Path.Combine(directory, fileName);
}
From your client, pass-in the directory (relative to the project) path of the file and then supply the file name for the second parameter.
In addition, it's probably good that you just create a library to manage various file operations.