I need to load a CSV file into a Neo4j database using its .NET driver. I can use the following code to load the file.
var dataFile = "data.csv";
var driver = GraphDatabase.Driver(uri, AuthTokens.Basic(user, password));
using var session = driver.AsyncSession(x => x.WithDefaultAccessMode(AccessMode.Write));
await session.WriteTransactionAsync(async tx =>
{
var result = await tx.RunAsync(
$"LOAD CSV WITH HEADERS FROM 'file:///{dataFile}' AS line " +
"CREATE(:Artist { name: line.Name, year: toInteger(line.Year)})");
});
This requires that the file is located under the C:/Users/user/.Neo4jDesktop/relate-data/dbmss/dbms-502b0f7e-04e2-4c24-9472-528775921429/import/ directory. If the data.csv file is located under a different directory, and I provide the fully quantifying path, I get the following error.
var dataFile = "C:/Users/user/Desktop/data.csv";
System.AggregateException: 'One or more errors occurred. (Couldn't load the external resource at: file:/C:/Users/user/.Neo4jDesktop/relate-data/dbmss/dbms-502b0f7e-04e2-4c24-9472-528775921429/import/Users/user/Desktop/data.csv)'
I can fix this by commenting-out dbms.directories.import=import in Neo4j config. However, in my usecase, modifying config is not an option and writing to the .Neo4jDesktop/relate-data/dbmss/dbms-***/import/ is not allowed.
Any thoughts on how I can load CSV from any directory without altering Neo4j configuration?
Changing the config file when importing a file outside "import" folder is a hard rule set by Neo4j. Please chase them about it thru
https://neo4j.com/contact-us/
Why importing file to import folder is not allowed?
Related
I am writing a web service which currently needs to read some settings from a json file on server.
string allSettingsTxt = File.ReadAllText(settingsPath);
List<MySetting> list = JsonConvert.DeserializeObject<List<MySetting>(allSettingsTxt);
I tried giving following for the path
string settingPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"..\MyCurrentDir\setting.json");
But this path wont resolve on the actual deployment, I believe it has to be something like http://servername/settings/setting.json ??
Where can I store such json file
what path I should use to access it?
I'm not totally sure if I understand correctly what you are trying to achieve.
I assume you want to get the path of the settings file which is relative to your executable file.
This is what I do often in my own code:
var configFile = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "config.xml");
In this case, config.xml is expected to be in the same directory as the .EXE.
So this would be
var settingPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), #"..\MyCurrentDir\setting.json");
in your case.
Also see https://dailydotnettips.com/different-ways-of-getting-path/ for some explanations.
I am trying to load an ONNX model using WinML, with the following code:
private async Task InitializeModelAsync()
{
var path = #"ms-appx:///Assets/FER-Emotion-Recognition.onnx";
var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri(path));
model = await CNTKGraphModel.CreateCNTKGraphModel(file);
}
The project compiles OK, but during run-time I am getting a System.IO.FileNotFoundException:
The system cannot find the file specified.
I double checked but the file is indeed in the right folder. What did I do wrong?
Right click on your onnx file, go to the Properties panel and set its Build Action to Content.
Then, set the Copy to Output Directory to Copy if newer.
See Get started with Machine Learning
I am trying to read a text file named thedata.txt that has a list of words that I want to use in a hangman game. I have tried different ways, but I can't figure out where the file gets placed, if at all when the app runs. I added the file to my project, and I have tried setting the build properties to content, and then embedded resource, but can't find the file. I have made a Windows 10 universal app project. The code I tried looks like this:
Stream stream = this.GetType().GetTypeInfo().Assembly.GetManifestResourceStream("thedata.txt");
using (StreamReader inputStream = new StreamReader(stream))
{
while (inputStream.Peek() >= 0)
{
Debug.WriteLine("the line is ", inputStream.ReadLine());
}
}
I get exceptions.
I also tried to list the files in another directory:
string path = Windows.Storage.ApplicationData.Current.LocalFolder.Path;
Debug.WriteLine("The path is " + path);
IReadOnlyCollection<StorageFile> files = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFilesAsync();
foreach (StorageFile file2 in files)
{
Debug.WriteLine("Name 2 is " + file2.Name + ", " + file2.DateCreated);
}
I don't see the file there either...I want to avoid hard coding the list of names in my program. I'm not sure what the path that the file is placed.
the code is very simple, you just have to use a valid scheme URI (ms-appx in your case) and transform your WinRT InputStream as a classic .NET stream :
var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///thedata.txt"));
using (var inputStream = await file.OpenReadAsync())
using (var classicStream = inputStream.AsStreamForRead())
using (var streamReader = new StreamReader(classicStream))
{
while (streamReader.Peek() >= 0)
{
Debug.WriteLine(string.Format("the line is {0}", streamReader.ReadLine()));
}
}
For the properties of the embedded file, "Build Action" must be set to "Content" and "Copy to Ouput Directory" should be set to "Do not Copy".
You can't use classic .NET IO methods in Windows Runtime apps, the proper way to read a text file in UWP is:
var file = await ApplicationData.Current.LocalFolder.GetFileAsync("data.txt");
var lines = await FileIO.ReadLinesAsync(file);
Also, you don't need a physical path of a folder - from msdn :
Don't rely on this property to access a folder, because a file system
path is not available for some folders. For example, in the following
cases, the folder may not have a file system path, or the file system
path may not be available. •The folder represents a container for a
group of files (for example, the return value from some overloads of
the GetFoldersAsync method) instead of an actual folder in the file
system. •The folder is backed by a URI. •The folder was picked by
using a file picker.
Please refer File access permissions for more details.
And Create, write, and read a file provides examples related with File IO for UWP apps on Windows 10.
You can retrieve a file directly from your app's local folder by using an app URI, like this:
using Windows.Storage;
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync("ms-appdata:///local/file.txt");
I'm making an application that loads and saves profile nodes to an external xml document in my output directory. It worked fine when I was opening it from my Assets folder but since that is read only (I think) I need to have it read and write from the output directory or another folder.
Like this:
XmlDocument users = new XmlDocument();
users.Load("users.xml");
However I get this error when this code runs:
"System.IO.FileNotFoundException: Could not find file "/users.xml"."
I've ticked the secondary storage permissions but i'm still a bit confused about just referencing a file in the output directory.
Would also appreciate the help for saving too as I assume the same error will occur:
users.DocumentElement.AppendChild(user);
users.Save("users.xml");
Thank you in advance.
In xamarin form you can try this code to load xml file from PCL project.
var assembly = typeof(TestClass).GetTypeInfo().Assembly;
Stream stream = assembly.GetManifestResourceStream(“PrjectName.FileName”);
using (var reader = new System.IO.StreamReader(stream))
{
var serializer = new XmlSerializer(typeof(List<BuildOptions>)); var listData = (List<T>)serializer.Deserialize(reader);
}
I am having an xml file like:
<CurrentProject>
// Elements like
// last opened project file to reopen it when app starts
// and more global project independend settings
</CurrentProject>
Now I asked myself wether I should deliver this xml file with above empty elements with the installer for my app or should I create this file on the fly on application start if it does not exist else read the values from it.
Consider also that the user could delete this file and that should my application not prevent from working anymore.
What is better and why?
UPDATE:
What I did felt ok for me so I post my code here :) It just creates the xml + structure on the fly with some security checks...
public ProjectService(IProjectDataProvider provider)
{
_provider = provider;
string applicationPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
_projectPath = Path.Combine(applicationPath,#"TBM\Settings.XML");
if (!File.Exists(_projectPath))
{
string dirPath = Path.Combine(applicationPath, #"TBM");
if (!Directory.Exists(dirPath))
Directory.CreateDirectory(dirPath);
using (var stream = File.Create(_projectPath))
{
XElement projectElement = new XElement("Project");
projectElement.Add(new XElement("DatabasePath"));
projectElement.Save(stream, SaveOptions.DisableFormatting);
}
}
}
In a similar scenario, I recently went for creating the initial file on the fly. The main reason I chose this was the fact that I wasn't depending on this file being there and being valid. As this was a file that's often read from/written to, there's a chance that it could get corrupted (e.g. if the power is lost while the file is being written).
In my code I attempted to open this file for reading and then read the data. If anywhere during these steps I encountered an error, I simply recreated the file with default values and displayed a corresponding message to the user.