I want to access a number of files in C#, and I haven't been able to succeed in doing so without hard-coding a path. I do not want to specify an exact path, as the program should work independent of its location.
I figured I should do this by adding the files to Resources, but I can't find how to iterate over those. I found several pages about reading .resx, but it seemed like all either only addressed accessing one specific resource by name, or used a hard-coded path.
The code I have currently is as follows:
ResXResourceReader resourcesreader = new ResXResourceReader(Properties.Resources);
This gives the compiler error "'Resources' is a type, which is not valid in the given context".
When I do hard-code a path, curiously, I get an error at runtime.
ResXResourceReader resourcesreader = new ResXResourceReader(#"G:\Programming\C#\Contest Judging\Contest Judging\Properties\Resources.resx");
foreach (DictionaryEntry image in resourcesreader)
At the bottom line, an exception is raised:
System.ArgumentException
ResX file Could not find a part of the path 'G:\Programming\C#\Contest Judging\Contest Judging\bin\Resources\BugsyWPfeiffer 1.png'. Line 123, position 5. cannot be parsed.
Inner Exception 1:
XmlException: Could not find a part of the path 'G:\Programming\C#\Contest Judging\Contest Judging\bin\Resources\BugsyWPfeiffer 1.png'. Line 123, position 5.
Inner Exception 2:
DirectoryNotFoundException: Could not find a part of the path 'G:\Programming\C#\Contest Judging\Contest Judging\bin\Resources\BugsyWPfeiffer 1.png'.
I wonder why it starts looking in bin\, as I did a Ctrl + F through Resources.resx and it does not occur.
You can do this by fetching the ResourceManager from the generated Resources class:
// Change this if you want to use fetch the resources for a specific culture
var culture = CultureInfo.InvariantCulture;
var resourceManager = Properties.Resources.ResourceManager;
var resourceSet = resourceManager.GetResourceSet(culture, createIfNotExists: true, tryParents: true);
foreach (DictionaryEntry entry in resourceSet)
{
Console.WriteLine($"{entry.Key}: {entry.Value}");
}
The resources are compiled into your application (or into satellite assemblies), so there's no resx file for you to load.
Related
I am trying to get reporting in C# to work. I'm trying to embed my rdlc file as such:
var reportDataSource = new ReportDataSource("ProspectsDataSet", _allProspects);
ReportViewer.LocalReport.DataSources.Add(reportDataSource);
ReportViewer.LocalReport.ReportEmbeddedResource = "SdcDatabase.Modules.EnquiryModule.View.Reports.ProspectsReport.rdlc";
ReportViewer.ZoomMode = ZoomMode.PageWidth;
ReportViewer.RefreshReport();
The build action on the rdlc file itself is set to embedded resource and the copy to output directory set to copy always.
I have double checked and I'm certain that that is the correct namespace in the ReportEmbeddedResource string. However when I try to load the report I get this error:
I have tried switching a few things around in the path, such as replacing '.' with '/' and '\' but so far I have not been able to get anything to fix this. I have also tried using LocalPath instead of EmbeddedResource but again I come across errors.
I have searched for this issue but haven't found anything to resolve my issue thus far.
I have a reporting wrapper class that works well for my apps. I have a property to hold the name of the ".rdlc" report definition I want to run. Then, when I call my "RunReport()" method, I assign the report based on reading a stream from my application assembly resource. A short version for what you have might be
ReportViewer.LocalReport.LoadReportDefinition( GetRDLCStream( "ProspectsReport.rdlc" ));
Then, lower, I have a method
private Stream GetRDLCStream( string rptRDLC)
{
var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(
"SdcDatabase.Modules.EnquiryModule.View.Reports." + rptRDLC);
return stream;
}
Obviously, I am not positive of the naming convention of your path to your project but am implying the above path. However, it should reflect (for example)
"NameOfYourApp.SubFolderWithinPath.MaybeReportsSubFolder." + actualReport.RDLC name
This way, I never have to worry about copying out a resource and hoping the paths work. I know it is embedded and where within the assembly.
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();
....
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Getting path relative to the current working directory?
I have code in C# that includes some images from an absolute path to a relative so the image can be found no matter where the application fold is located.
For example the path in my code (and in my laptop for the image) is
C:/something/res/images/image1.jpeg
and I want the path in my code to be
..../images/image1.jpeg
So it can run wherever the folder is put, whatever the name of the C: partition is etc.
I want to have a path in my code which is independant of the application folder location or if it is in another partition, as long as it is in the same folder as the the rest of the solution.
I have this code:
try
{
File.Delete("C:/JPD/SCRAT/Desktop/Project/Resources/images/image1.jpeg");
}
catch (Exception)
{
MessageBox.Show("File not found:C:/Users/JPD/Desktop/Project/images/image1.jpeg");
}
This code only runs if the file and folder are in that certain path, (which is also the location of the code) I wish for that path to be relative so wherever I put the whole folder (code, files etc) the program will still work as long as the code (which is under project folder) is at the same location with the folder images... what should I do?
Relative paths are based from the binary file from which your application is running. By default, your binary files will be outputted in the [directory of your .csproj]/bin/debug. So let's say you wanted to create your images folder at the same level as your .csproj. Then you could access your images using the relative path "../../images/someImage.jpg".
To get a better feel for this, try out the following as a test:
1) create a new visual studio sample project,
2) create an images folder at the same level as the .csproj
3) put some files in the images folder
4) put this sample code in your main method -
static void Main(string[] args)
{
Console.WriteLine(Directory.GetCurrentDirectory());
foreach (string s in Directory.EnumerateFiles("../../images/"))
{
Console.WriteLine(s);
}
Console.ReadLine(); // Just to keep the console from disappearing.
}
You should see the relative paths of all the files you placed in step (3).
see: Getting path relative to the current working directory?
Uri uri1 = new Uri(#"c:\foo\bar\blop\blap");
Uri uri2 = new Uri(#"c:\foo\bar\");
string relativePath = uri2.MakeRelativeUri(uri1).ToString();
Depending on the set up of your program, you might be able to simply use a relative path by skipping a part of the full path string. It's not braggable, so J. Skit might be up my shiny for it but I'm getting the impression that you simply want to make it work. Beauty being a later concern.
String absolutePath = #"c:\beep\boop\HereWeStart\hopp.gif";
String relativePath = absolutePath.Substring(13);
You could then, if you need/wish, exchange the number 13 (which is an ugly and undesirable approach, still working, though) for a dynamically computed one. For instance (assuming that the directory "HereWeStart", where your relative path is starting, is the first occurrence of that string in absolutePath) you could go as follows.
String absolutePath = #"c:\beep\boop\HereWeStart\hopp.gif";
int relativePathStartIndex = absolutePath.IndexOf("HereWeStart");
String relativePath = absolutePath.Substring(relativePathStartIndex);
Also, your question begs an other question. I'd like to know how you're obtaining the absolute path. Perhaps there's an even more clever way to avoid the hustle all together?
EDIT
You could also try the following approach. Forget the Directory class giving you an absolute path. Go for the relative path straight off. I'm assuming that all the files you're attempting to remove are in the same directory. If not, you'll need to add some more lines but we'll cross that bridge when we get there.
Don't forget to mark an answer as green-checked (or explain what's missing or improvable still).
String
deletableTarget = #"\images\image1.jpeg",
hereWeAre = Environment.CurrentDirectory;
MessageBox.Show("The taget path is:\n" + hereWeAre + deletableTarget);
try
{ File.Delete(hereWeAre + deletableTarget); }
catch (Exception exception)
{ MessageBox.Show(exception.Message); }
Also, please note that I took the liberty of changing your exception handling. While yours is working, it's a better style to rely on the built-in messaging system. That way you'll get more professionally looking error messages. Not that we ever get any errors at run-time, right? ;)
I want to get the number of pictures that is in a folder on a website. But I can't find a way to do it.
I have tried to use
string a = Request.QueryString["nr"];
string[] filePaths = Directory.GetFiles(#"URL" + a, a + "_profil*");
But it doesn't work. I get the error:
Exception Details: System.ArgumentException: URI formats are not supported.
It is expecting the path to the folder on the file system, e.g. c:\some\folder\. Depending on what you're doing, you might be able to use Server.MapPath("~/some/folder") to resolve the full path.
Here's my code when retrieving the resource file.
ResourceManager resourceManager = ResourceManager.CreateFileBasedResourceManager("Resource.resx", #"c:\", null);
resourceValue = resourceManager.GetString("key1");
But I got this exception everytime I run this.
Could not find any resources
appropriate for the specified culture
(or the neutral culture) on disk.
baseName: Resources.resx
locationInfo: null fileName:
Resources.resx.resources
What's wrong in my code?
Steven is right, it's looking for a .ressources file. You need to compile your resx file with resgen : http://msdn.microsoft.com/en-us/library/ccec7sz1(v=vs.71).aspx
Some more info : the resx file is just a file that describes how to create a resources file. When you compile it (is compile the right word ?) with resgen, it takes all images, texts, etc.. and merge them in the real resource file that you can distribute and work with.
I suggest the following read, it may help : http://edndoc.esri.com/arcobjects/9.1/ArcGISDevHelp/DevelopmentEnvs/DotNet/WorkingWithResources.htm
It is looking for a different file, as mentioned on msdn, and in your exception message.
baseName
Type: System.String
The root name of the resources. For example, the root name for the
resource file named
"MyResource.en-US.resources" is
"MyResource".
Your file should be named "Resource.resources", when passing "Resource" as baseName to the method. When you want custom resources for different cultures, you should name them like "Resource.en-US.resources" where the "en-US" part is replaced by the desired ISO culture name.