I am trying to make an application which checks whether a word is a valid dictionary word.
NetSpell.SpellChecker.Dictionary.WordDictionary oDict = new NetSpell.SpellChecker.Dictionary.WordDictionary();
oDict.DictionaryFile = "en-US.dic";
oDict.Initialize(); // file not found exception
string wordToCheck = "door";
NetSpell.SpellChecker.Spelling oSpell = new NetSpell.SpellChecker.Spelling();
oSpell.Dictionary = oDict;
if(oSpell.TestWord(wordToCheck))
{
//Word exist in dictionary
...
}
I have tried giving all possible file locations like ".\en-US.dic" to "C:\Program Files\IIS Express\en-US.dic" but i still get file not found exception. Can anyone help me in figuring where the file actually is.
When you install netSpell using nuget a new folder is created by the name 'Packages'. All the .dic (dictionary) files are stored in that folder.
You need to use a relative path using Server.MapPath:
If the file en-US.dic is in your root directory, use:
oDict.DictionaryFile = Server.MapPath("en-US.dic");
If the file en-US.dic is nested under some other directory, use:
oDict.DictionaryFile = Server.MapPath("/SomeDirectory/en-US.dic");
Related
I want to get the path of a specific folder inside the solution.
Ive tried to find answers on stack overflow, but i guess my concentration is already near the end and i cant find a real usefull answer.
Here is the folder i want (KeePassFiles):
I had those 2 files on the desktop before and reading them worked. But now i have to add those files into one of the solution folder and i only want to get the path for that.
It should work for different users who download that project.
My code right now for the desktop solution is:
string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
var dbpath = #$"{desktopPath}\KeePassDatabase\Database.kdbx";
var keypath = #$"{desktopPath}\KeePassDatabase\Database.key";
Now it should be something like:
string solutionKPPath = Environment.GetFolderPath(path for solution);
var dbpath = #$"{solutionKPPath}\KeePassFiles\Database.kdbx";
var keypath = #$"{solutionKPPath}\KeePassFiles\Database.key";
Environment.CurrentDirectory will return the Debug directory or the Release directory depending on your run configuration. As far as I know, there is no easy way to get a specific folder or file in your solution. The best solution I could think of is using something like the following to get the solution directory:
public static DirectoryInfo TryGetSolutionDirectoryInfo(string currentPath = null)
{
var directory = new DirectoryInfo(
currentPath ?? Directory.GetCurrentDirectory());
while (directory != null && !directory.GetFiles("*.sln").Any())
{
directory = directory.Parent;
}
return directory;
}
And then use that path to dig into your folders and find the specific file you're looking for using something like Path.Combine(...).
In your case, don't pass any parameters to this method if you want it to retrieve the Debug/Release directory and search up from there
Edit: Note that this will actually not work for production since there will be no .sln file to find. As suggested by the comments on your question, you should configure your project to copy the necessary files into the output folder and therefore Environment.CurrentDirectory will do the trick
I think you should not get the files from the project source, you should copy them to the output during build and then get them from output location.
I would recommend to use "Copy to Output directory= Copy Allways" and than identify the "Execution Path" by use of AppDomain.CurrentDomain.BaseDirectory or Assembly.GetEntryAssembly().Location
If you using Unit Test, especially MS UnitTests it may be necessary to use `[DeploymentItem(#"\Shared\Keepassfiles\Database.kdbx")]
We have set of Test projects under one solution in Visual Studio. I want to read a Json file which is copied to the output directory from a different project folder in runtime. It's a test project. I can get the current project directory. But not sure how to get the other assembly's directory.
Solution looks as below
Project1 -> Sample.json (this file is set to copy to output directory)
Project2
While running my test in Project2 I want to access the file in Project1 from the output directory.
I used to access files in the same project folder with code as mentioned. But not sure how to get for a different project file. Now with replace I am able to achieve it. But sure this is not the right way
var filePath = Path.Combine("Sample.json");
var fullPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), filePath).Replace("Project1", "Project2");
Not sure how to get from other project. I am sure I can't use GetExecutingAssembly(), but what is the alternative. Somehow I can access it using the above dirty way of replacing the assembly name.
To get the location of another assembly, you get use a type from that assembly to get to the right Assembly instance, and thus its location:
typeof(FromOtherAssembly).Assembly.Location
First, I suggest that you could find the dll path in the solution.
Second, you can filter the json file from the path.
The next is my working code.
Please install Microsoft.Build and Microsoft.Build.Framework nugetpackages first.
string path= string.Empty;
var solutionFile =SolutionFile.Parse(#"D:\test.sln");// Your solution place.
var projectsInSolution = solutionFile.ProjectsInOrder;
foreach (var project in projectsInSolution)
{
if(project.ProjectName=="TestDLL") //your dll name
{
path = project.AbsolutePath;
DirectoryInfo di = new DirectoryInfo(string.Format(#"{0}..\..\", path));
path = di.FullName;
foreach (var item in Directory.GetFiles(path,"*.json")) // filter the josn file in the correct path
{
if(item.StartsWith("Sample"))
{
Console.WriteLine(item);// you will get the correct json file path
}
}
}
}
You can use the below code to do it in a better way
//solutionpath will take you to the root directory which has the .sln file
string solutionpath = Path.Combine(Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.FullName);
string secondprojectname = #"SecondProjectName\bin";
string finalPath = Path.Combine(solutionpath, secondprojectname);
you can use CopyToOutputDirectory in MSBuild
I using .Net Framework 4.0; VS 2015; Ionic.Zip.Reduced (DotNetZip.Reduced) v1.9.1.8. When I try to add a folder to the archive get an exception with the text:
The path is too long
Sample code:
using (var zipFile = new ZipFile(zipFilePath))
{
zipFile.UseZip64WhenSaving = Zip64Option.AsNecessary;
zipFile.AlternateEncodingUsage = ZipOption.Always;
zipFile.AlternateEncoding = Encoding.UTF8;
zipFile.ParallelDeflateThreshold = -1;
var dirPath = #"C:\AAAAAAAAAAA\AAAAAA\AAAAAAAAAAAAAAA\AAAAAAAAA\AAAAAAAAAAAAA\AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\";
zipFile.AddDirectory(dirPath); <-Exception
zipFile.Save();
}
In the folder is a file named: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA.zip
As a result of an error:
The path is too long
Rewritten in the file-based addition to the archive (using a relative path):
using (var zipFile = new ZipFile(zipFilePath))
{
zipFile.UseZip64WhenSaving = Zip64Option.AsNecessary;
zipFile.AlternateEncodingUsage = ZipOption.Always;
zipFile.AlternateEncoding = Encoding.UTF8;
zipFile.ParallelDeflateThreshold = -1;
var dirPath = #"C:\AAAAAAAAAAA\AAAAAA\AAAAAAAAAAAAAAA\AAAAAAAAA\AAAAAAAAAAAAA\AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\";
Directory.SetCurrentDirectory(dirPath);
var files = Directory.GetFiles(dirPath, "*", SearchOption.AllDirectories).ToArray();
foreach (var fullFilePath in files)
{
var fileName = Path.GetFileName(fullFilePath);
var relatedPath = fullFilePath.Substring(0, fullFilePath.LastIndexOf(fileName, StringComparison.InvariantCultureIgnoreCase)).Replace(zipDir, "");
var relatedFilePath = Path.Combine(relatedPath, fileName);
zipFile.AddFile(relatedFilePath); <-Exception
}
zipFile.Save();
}
The error is the same:
The path is too long
I tried to call Path.GetDirectoryName() method, but it also returns an error:
The specified path, file name, or both are too long. The fully
qualified file name must be less than 260 characters, and the
directory name must be less than 248 characters.
I found a lot of solutions but to get to work and did not work (because of the specifics of the application to the new version Framework'a can not go).
Use Framework 4.6.2. Set UseLegacyPathHandling = false option in App.Config or Switch.System.IO.UseLegacyPathHandling = false; Switch.System.IO.BlockLongPaths = false
With the mention of a Group Policy and the inclusion of the option Configuration> Administrative Templates> System> Filesystem> Enable NTFS long paths, or to enable the option via the manifest <ws2:longPathAware>true</ws2:longPathAware>
Use the prefix \\?\ In the path (I understand that for the new version of Framework)
Convert path to the file in 8.3 format using GetShortPathName function .... (Error remains)
Maybe someone faced such problem. I will be glad to any advice. Thanks.
If your path is too long there's not much you can do about it. Even if you can move Windows limits a step further your application won't work well on a non ad-hoc configured system in that scenario.
You can workaround copying the files you have to work with to a temp folder like C:\temp and add the files to the archive from there.
You can even mimic the same folder tree structure with directory names composed of only 1 or 2 letters and then map the complete (but really shorter) directory path to the original path somewhere (on a file for example), so that you can rebuild the original folder tree structure with the same names later on.
I want to load a xml document Swedish.xml which exists in my solution. How can i give path for that file in Xamarin.android
I am using following code:
var text = File.ReadAllText("Languages/Swedish.txt");
Console.WriteLine("text: "+text);
But i am getting Exception message:
Could not find a part of the path "//Languages/swedish.txt".
I even tried following lines:
var text = File.ReadAllText("./Languages/Swedish.txt");
var text = File.ReadAllText("./MyProject/Languages/Swedish.txt");
var text = File.ReadAllText("MyProject/Languages/Swedish.txt");
But none of them worked. Same exception message is appearing. Build Action is also set as Content. Whats wrong with the path? Thanks in advance.
Just try with this
string startupPath = Path.Combine(Directory.GetParent(System.IO.Directory.GetCurrentDirectory()).Parent.Parent.FullName, "Languages", "Swedish.txt");
var text = File.ReadAllText(startupPath);
Try...
Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments)+"/Languages/Swedish.txt"
If you mark a file as Content Type, it will be included in the app bundle with the path that you are using within your project file. You can inspect the IPA file (it's just a renamed zip) that is created to verify that this is happening.
var text = File.ReadAllText("Languages/Swedish.txt");
should work. The file path is relative to the root of your application. You need to be sure that you are using the exact same casing in your code that the actual file uses. In the simulator the casing will not matter, but on the device the file system is case sensitive, and mismatched casing will break the app.
I've looked into this before and never found any solution to access files in this way. All roads seem to indicate building them as "content" is a dead end. You can however place them in your "Assets" folder and use them this way. To do so switch the "Content" to "AndroidAsset".
After you have done this you can now access the file within your app by calling it via
var filename = "Sweedish.txt";
string data;
using
(var sr = new StreamReader(Context.Assets.Open(code)))
data = sr.ReadToEnd();
....
In my app I have a WebBrowser element.
I would like to load a local file in it.
I have some questions:
Where to place the HTML file (so that it will also be installed if a user executes the setup)
how to reference the file? (e.g. my guess is the user's installation folder would not always be the same)
EDIT
I've added the HTML file to my project.
And I have set it up so that it gets copied to output folder.
When I check it it is present when run: \bin\Debug\Documentation\index.html
However when I do the following I get a 'Page cannot be displayed' error in the webbrowser element.
I use the following code to try to display the HTML file in the Webbrowser.
webBrowser1.Navigate(#".\Documentation\index.html");
Do a right click->properties on the file in Visual Studio.
Set the Copy to Output Directory to Copy always.
Then you will be able to reference your files by using a path such as #".\my_html.html"
Copy to Output Directory will put the file in the same folder as your binary dlls when the project is built. This works with any content file, even if its in a sub folder.
If you use a sub folder, that too will be copied in to the bin folder so your path would then be #".\my_subfolder\my_html.html"
In order to create a URI you can use locally (instead of served via the web), you'll need to use the file protocol, using the base directory of your binary - note: this will only work if you set the Copy to Ouptut Directory as above or the path will not be correct.
This is what you need:
string curDir = Directory.GetCurrentDirectory();
this.webBrowser1.Url = new Uri(String.Format("file:///{0}/my_html.html", curDir));
You'll have to change the variables and names of course.
quite late but it's the first hit i found from google
Instead of using the current directory or getting the assembly, just use the Application.ExecutablePath property:
//using System.IO;
string applicationDirectory = Path.GetDirectoryName(Application.ExecutablePath);
string myFile = Path.Combine(applicationDirectory, "Sample.html");
webMain.Url = new Uri("file:///" + myFile);
Note that the file:/// scheme does not work on the compact framework, at least it doesn't with 5.0.
You will need to use the following:
string appDir = Path.GetDirectoryName(
Assembly.GetExecutingAssembly().GetName().CodeBase);
webBrowser1.Url = new Uri(Path.Combine(appDir, #"Documentation\index.html"));
Place it in the Applications setup folder or in a separte folder beneath
Reference it relative to the current directory when your app runs.
Somewhere, nearby the assembly you're going to run.
Use reflection to get path to your executing assembly, then do some magic to locate your HTML file.
Like this:
var myAssembly = System.Reflection.Assembly.GetEntryAssembly();
var myAssemblyLocation = System.IO.Path.GetDirectoryName(a.Location);
var myHtmlPath = Path.Combine(myAssemblyLocation, "my.html");
What worked for me was
<WebBrowser Source="pack://siteoforigin:,,,/StartPage.html" />
from here. I copied StartPage.html to the same output directory as the xaml-file and it loaded it from that relative path.
Windows 10 uwp application.
Try this:
webview.Navigate(new Uri("ms-appx-web:///index.html"));
Update on #ghostJago answer above
for me it worked as the following lines in VS2017
string curDir = Directory.GetCurrentDirectory();
this.webBrowser1.Navigate(new Uri(String.Format("file:///{0}/my_html.html", curDir)));
I have been trying different answers from here, but managed to derive something working, here it is:
1- Added the page in a folder i created at project level named WebPagesHelper
2- To have the page printed by webBrowser Control,
string curDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
var uri = new Uri(curDirectory);
string myFile = Path.Combine(uri.AbsolutePath, #"WebPagesHelper\index.html");
Uri new_uri = new Uri(myFile);
i had to get the assembly path, create a first uri to get an absolute path without the 'file://' attached, next i combined this absolute path with a relative path to the page in its folder, then made another URI from the result.
Then pass this to webBrowser URL property webBrowser.URL = new_uri;