System.Exception: Shape file not found: [PATH] - c#

When this method is invoked I get the following stack trace when it reaches OpenAsync():
System.Exception: Shape file not found:
C:\Users\Laura\Desktop\shapes\TOTALMAP\OH_Line_6600v_Expired.shp at
RuntimeCoreNet.Interop.HandleException(Boolean retVal) at
RuntimeCoreNet.CoreFeatureSource.FromShapefile(String filename) at
Esri.ArcGISRuntime.Data.ShapefileTable.OpenAsync(String filename)
at ShapeSQLiteGISDemo.MainPage.d__3.MoveNext()
I have a .dbf and .shx file in the same folder with the same name and I've been running Visual Studio in Administrator Mode.
private async void ImportShapes(object sender, RoutedEventArgs e)
{
try
{
//Get path from file picker
var picker = new FileOpenPicker { SuggestedStartLocation = PickerLocationId.Desktop };
picker.FileTypeFilter.Clear();
picker.FileTypeFilter.Add(".shp");
var file = await picker.PickSingleFileAsync();
//convert folder contents to a ShapefileTable
var shapefile = await ShapefileTable.OpenAsync(file.Path);
//save object to database
_DatabaseConnection.Insert(shapefile);
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
//call a method that loads shapes from the database
LoadDatabaseOntoMap();
}
Any help much appreciated.

I believe the problem is that with Store and UWP apps the .shp file has to be moved to a folder in the local storage before the application can open it.
Will set as the accepted answer if this solves the problem.
EDIT: This is indeed the case, because I was choosing a single file with the the file picker I only had access to that one file. To get multiple files I used the folder picker and filtered away any files that weren't useful.

Try using an app like notepad to open the file by pasting in the path:
C:\Users\Laura\Desktop\shapes\TOTALMAP\OH_Line_6600v_Expired.shp
Does the app open the file?
Are there other examples of shape files that do open? Could this file simply be corrupted?

Related

UWP StorageFolder access to the Downloads folder

I have done a ton of research on MSDN and SO but there seem to be a lot of mixed reviews on this topic and no straightforward answer. My UWP app needs to download some items for the user. It seems only logical that this goes into the "downloads" folder instead of Documents or Pictures.
What I gather from my reading is that an application is allowed to access the downloads folder and create files and sub folders within the downloads folder. However, it cannot access other files and folder (not created from your app) without the use of a picker. In this case, I should not need to use a picker because my app is using the and creating the folder for itself. I have also read, there is not need for special capabilities in the Manifest for this to work.
I can confirm that this does in fact work by creating a folder and a file in the downloads folder
StorageFile destinationFile;
StorageFolder downloadsFolder;
try
{
//Create a sub folder in downloads
try
{
downloadsFolder = await DownloadsFolder.CreateFolderAsync("AppFiles");
}
catch (Exception ex)
{
//HERE IS THE ISSUE. I get in here if the folder exists but how do i get it?
}
destinationFile = await downloadsFolder.CreateFileAsync(destination,CreationCollisionOption.GenerateUniqueName);
}
catch (FileNotFoundException ex)
{
rootPage.NotifyUser("Error while creating file: " + ex.Message, NotifyType.ErrorMessage);
return;
}
However, here is the major issue. This code works fine the first time through because the folder does not already exist and it creates it along with the file. Subsequent times through, it fails and throws an exception:
Cannot create a file when that file already exists. (Exception from HRESULT: 0x800700B7)
It does this on the line to create the folder in Downloads folder:
downloadsFolder = await DownloadsFolder.CreateFolderAsync("AppFiles");
The problem is that MSDN states that I cannot use the Collision options of "OpenIfExists" or "ReplaceExisting" which are the two collision options I would need to solve this problem. The two remaining options do no good for me. So, no matter what, it is going to throw an exception if the folder exists.
Then, the thought is that I could just catch the exception, like I am already doing in my snippet above and open the folder if it exists. The problem with this is that the "DownloadsFolder" class does not give any options to get or open a folder, only to create a folder.
So, it seems I can create the folder from my app but I cannot open or get the folder that my app created?
Thanks!
The problem with this is that the "DownloadsFolder" class does not give any options to get or open a folder, only to create a folder.
Actually, When you first run your code, you could create your folder successfully and get the folder instance to create file in this folder. But why you could not get it when it's existed, it's by design.
I believe you have checked the document:
Because the app can only access folders in the Downloads folder that it created, you can't specify OpenIfExists or ReplaceExisting for this parameter.
So, How to get the folder that you created? I will tell you in the following:)
In this case, I should not need to use a picker because my app is using the and creating the folder for itself.
As you said, the first option is to use a picker, but you've said that you do not want to use a picker. Then, I will give you another option.
When you first create the folder successfully, you could add this folder to the FutureAccessList. Then, you could get this folder directly in your code.
I've made a simple code sample for your reference:
StorageFile destinationFile;
StorageFolder downloadsFolder;
try
{
try
{
downloadsFolder = await DownloadsFolder.CreateFolderAsync("AppFiles");
string folderToken = Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.Add(downloadsFolder);
ApplicationData.Current.LocalSettings.Values["folderToken"] = folderToken;
destinationFile = await downloadsFolder.CreateFileAsync("destination.txt", CreationCollisionOption.GenerateUniqueName);
}
catch (Exception ex)
{
if (ApplicationData.Current.LocalSettings.Values["folderToken"] != null)
{
string token = ApplicationData.Current.LocalSettings.Values["folderToken"].ToString();
downloadsFolder = await Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.GetFolderAsync(token);
destinationFile = await downloadsFolder.CreateFileAsync("destination.txt", CreationCollisionOption.GenerateUniqueName);
}
}
}
catch (FileNotFoundException ex)
{
rootPage.NotifyUser("Error while creating file: " + ex.Message, NotifyType.ErrorMessage);
return;
}

ReadLinesAsync in UWP from absolute file path

I get error
The filename, directory name, or volume label syntax is incorrect. (Exception from HRESULT: 0x8007007B)
My code is
public async void ReadFile()
{
var path = #"F:\VS\WriteLines.xls";
var folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
var file = await folder.GetFileAsync(path);
var readFile = await Windows.Storage.FileIO.ReadLinesAsync(file);
foreach (var line in readFile.OrderBy(line =>
{
int lineNo;
var success = int.TryParse(line.Split(';')[4], out lineNo);
if (success) return lineNo;
return int.MaxValue;
}))
{
itemsControl.Items.Add(line);
}
}
The error shows up at var file = await folder.GetFileAsync(path);
You cannot read a file from an arbitrary location on disk in a UWP App.
There are a couple of ways you can still accomplish your task:
You can add the WriteLines.xls file to your project and set it's build action to Content and Copy to output Directory to Copy if newer. You can then access the file with the code you have by simply replacing the "path" value to:
var path = #"WriteLines.xls"
More details here
If you need to be able to read any files from disk, you need to either use a FilePicker to select the file or copy the file in the Documents Folder and change the folder to:
var folder = KnownFolders.DocumentsLibrary;
More details here
You are asking for file with absolute path from application's local folder - hence it throws that error as you provide path that includes drive name.
In general UWP is very restrictive on where/how you can get files from - I don't think you can get it from absolute path in the sample (app needs more permissions to get to similar places). You can try StorageFile.GetFileFromPathAsync.
Detailed info on locations app can access - UWP apps on Windows 10: File access permissions.

After writing, the file is not modified on Windows Phone 8.0

During the execution of this script it is not detected any error, but the file isn't modified. Reading works, writing strangely not.
My script for writing:
private void firstLaunch(){
try {
StreamWriter outfile = new StreamWriter("Path/something.txt");
outfile.WriteLine("somethingElse");
outfile.Close();
}
catch (IOException ex){
MessageBox.Show(ex.Message);
}
}
The file already exists and has already been included in the project with visual studio. At the moment it is completely empty.
Could you help me?
You can use something like this:
var res = App.GetResourceStream(new Uri("test.txt", UriKind.Relative));
var txt = new StreamReader(res.Stream).ReadToEnd();
Just make sure that the file has the Build Action set to Content.
If the file is empty, I would recommend creating one in the folder of your app using IsolatedStorage. That way you can check with IsoStoreSpy the contents of your file.

Argument Null Exception error when trying to create a Text File

Problem:
I am trying to create a text file from a web service (local host), but on creation it gets the null argument error for path location. Now I am still using 2012 and was under the impression the code I gave would return the path name, but just returns null.
Aim:
Create a new file if one doesn't exist.
Get the path of the file for future use.
Question:
What are the visual studio 2012 C# methods for creating a text file? I find allot of sources but the code doesn't seem to work with 2012.
My Code:
//Create a file name for the path
string path = System.IO.Path.Combine(CurrentDirectory, "textFile.txt");
//Check if it exist, if not then create the File
//This is the recommended code by Microsoft
if (!System.IO.File.Exists(path))
{
System.IO.File.Create(path);
}
Get the file path using Server.Map path
string FolderPath = Server.MapPath("~/App_Data");
string file = Path.Combine(FolderPath, "textFile.txt");
//Check if it exist, if not then create the File
//This is the recommended code by Microsoft
if (!System.IO.File.Exists(file))
{
System.IO.File.Create(file);
}
Also check if the IIS user have permission to write on that folder (Add permission to the application pool user)
If you are trying to write something on a txt file, these piece of code does. No need to create a file if it is not exist. These code will create a file automatically if it not exists.
public static void LogMessage(string sFilePath, string sMsg)
{
using (StreamWriter sw = File.AppendText(sFilePath))
{
sw.WriteLine(string.Format(#"{0} : {1}", DateTime.Now.ToLongTimeString(), sMsg));
}
}
Are you sure CurrentDirectory value is right?
If you want visit current Web Service root dir can use like AppDomain.CurrentDomain.BaseDirectory.

Get full file path including file's name from an uploaded file in C#

I have this web application project which requires a better user-interface and I am doing it by C#.
I already have my html file with JS done but I need some data from user.
In my JS embedded in HTML file, I used the code below to find the file on local driver and get the data from that excel file and then put all these data into an array.
var excel = new ActiveXObject("Excel.Application");
var excel_file = excel.Workbooks.Open(file1);
var excel_sheet = excel.Worksheets("Sheet1");
However, the "file1" you see above seems to require a full name path,say "C:\test.xls" in my case.
I am new to C# and just built a button on my form design, by clicking the button, I seem to be able to browse my local file.
private void button1_Click(object sender, EventArgs e)
{
int size = -1;
DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
if (result == DialogResult.OK) // Test result.
{
string file = openFileDialog1.FileName;
try
{
string text = File.ReadAllText(file);
size = text.Length;
}
catch (IOException)
{
}
System.Diagnostics.Process.Start(file);
}
Console.WriteLine(size); // <-- Shows file size in debugging mode.
Console.WriteLine(result); // <-- For debugging use.
}
So, my question:
How can I get this kind of full file path of an uploaded file in C# ?
And furthermore, it would be awesome if some one can tell me how to get this value into my javascript or HTML!
Thank you in advance
You won't be able to depend on getting the full path. In the end, the browser only needs to multi-part encode the physical file and submit it as a form post (of sorts). So once it has it's location and has encoded it -- it's done using it.
It's considered a security risk to expose the file structure to Javascript/HTML (ie., the internet).
Just an update.
I used another logic and it worked as expected. Instead of getting absolute file path , I managed to open the file , save it as somewhere and make my html call find that file path no matter what.

Categories