Trying to find the path to my file after adding it to properties is not working very well. In my properties the file looks like this:
internal static System.Drawing.Bitmap one {
get {
object obj = ResourceManager.GetObject("one", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
How can I find the path to this file?
And then I try to use it like this:
System.Reflection.Assembly thisExe;
thisExe = System.Reflection.Assembly.GetExecutingAssembly();
System.IO.Stream file =
thisExe.GetManifestResourceStream("WindowsFormsApplication1.Properties.Resources.one");
this.pictureBox1.Image = Image.FromStream(file);
When I run this code:
System.Reflection.Assembly thisExe;
thisExe = System.Reflection.Assembly.GetExecutingAssembly();
string [] resources = thisExe.GetManifestResourceNames();
string list = "";
// Build the string of resources.
foreach (string resource in resources)
list += resource + "\r\n";
It gives me the following paths: "WFA1.Form1.resources" and "WFA1.Properties.Resources.resources"
Can add that my recourses are embedded.
If you need any more info please let me know.
So what I want is a path to my file, or info on HOW I can find the path. After looking around they say this should work:
System.IO.Stream file =
thisExe.GetManifestResourceStream("[WindowsFormsApplication1.Form1.resources].[a.jpg]");
IE:
System.IO.Stream file =
thisExe.GetManifestResourceStream("[Namespace].[file and extension]");
So it seems Im getting my namespace wrong cus it still returns null at this line:
this.pictureBox1.Image = Image.FromStream(file);
I have had a look at this and I don't believe that there's a way to get the path without some serious string building/manipulation. Which of course could lead to bigger issues.
I presume this code will not suffice:
var bmp = new Bitmap(WindowsFormsApplication1.Properties.Resources.one);
pictureBox1.Image = bmp;
Instead of this one:
var thisExe = Assembly.GetExecutingAssembly();
var file = thisExe.GetManifestResourceStream("WindowsFormsApplication1.Properties.Resources.one");
if (file != null) pictureBox1.Image = Image.FromStream(file);
Option 2:
var assembly = System.Reflection.Assembly.GetExecutingAssembly();
var stream = assembly.GetManifestResourceStream("WindowsFormsApplication1.Properties.Resources.one.jpg");
var tempPath = Path.GetTempPath();
File.Save(stream, tempPath);
Related
I have added a resource file to my project (C#, windows service - TopShelp):
I have added a text file to the resource:
Now I want to read the test file, this is what I have tried:
ResourceManager rm = new ResourceManager("My.Project.Name.Resources", Assembly.GetExecutingAssembly());
It does not find anything, ResourceSets count = 0.
Update
As suggested in the comments, I also tried adding the resource under:
Project > Properties > Resources
And tried the following code, which did not find anything:
ResourceManager rm = new ResourceManager("My.Project.Name.Resources", Assembly.GetExecutingAssembly());
Check your Resources.Designer.cs file. You should have there static string property named stop_words_utf8 (or whatever name for the file you choose). You use it like this:
Resources.stop_words_utf8
It is static string property
You can always try:
var assembly = Assembly.GetExecutingAssembly();
var resourceName = "MyCompany.MyProduct.MyFile.txt";
using (Stream stream = assembly.GetManifestResourceStream(resourceName))
using (StreamReader reader = new StreamReader(stream))
{
string result = reader.ReadToEnd();
}
Check that your file exists through Assembly.GetManifestResourceNames method.
I want to read a CSV file which is located at the same directory as my code.
I want to read the content of the .csv
public static void InitializeItems()
{
itemList = new Dictionary<int, Item>();
string filePath = Path.Combine(Directory.GetCurrentDirectory(), "\\Items.csv");
using (StreamReader reader = new StreamReader(filePath))
{
int lineCounter = 0; // Do I really need such a counter for the current line?
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
string[] values = line.Split(',');
string name = values[0];
itemList.Add(lineCounter, new Item(name));
lineCounter++;
}
}
}
private static Dictionary<int, Item> itemList;
By doing so I get a System.IO.FileNotFoundException exception. The file C:\Items.csv does not exist.
Directory.GetCurrentDirectory() returns me the path to the .exe file.
What is wrong with the path?
Current directory is not necessary the directory where exe has been executed:
// Current directory can be whatever you want:
Environment.CurrentDirectory = #"c:\SomeDirectory";
If you are looking for the exe path you can try
string exePath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
In your case:
using System.Reflection;
...
string filePath = Path.Combine(
Path.GetDirectoryName(Assembly.GetEntryAssembly().Location),
"Items.csv");
Edit: You can simplify the code (get rid of StreamReader) with a help of Linq:
var itemList = File
.ReadLines(filePath)
.Select((line, index) => new {
value = new Item(line.SubString(0, line.IndexOf(',') + 1)),
index = index
})
.ToDictionary(item => item.index, item => item.value);
The way to get the path of the .exe file like:
AppDomain.CurrentDomain.BaseDirectory
Then, you must put BuildAction as Content. With this, the file is copied to the folder exe after build.
var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "file.csv");
To answer your direct question, what is wrong: You can not have your file starting with a backslash when using Path.Combine. You should write it as this:
string filePath = Path.Combine(Directory.GetCurrentDirectory(), "Items.csv");
Edit:
By default the 'CurrentDirectory' points to your exe file, unless you change it in code or in a shortcut.
First it is advisable to create a new folder in your project to store files and name it MyFiles,
then lets say your file is a csvfile and named test.csv
so this can be accessed like this :
string testFilePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), #"MyFiles\test.csv");
I have a number of small PowerPoint files in my resources folder and I want to open them. I'm having issues doing this as my Resource.sendToPPTTemp is of type byte[] and to open the file I need it as a string. Is there a way I can open a file from resources as a string?
var file = Resources.sendToPPTTemp;
ppnt.Application ppntApplication = new ppnt.Application();
var _assembly = Assembly.GetExecutingAssembly();
var myppnt = ppntApplication.Presentations.Open(file.ToString());
ppntApplication.Visible = MsoTriState.msoTrue;
You need to give the path to your file to the Open method, not the binary representation. Either you have the path and pass it to the method or you have to create a file with your byte[].
I'd rather create a folder with all your PPT and store in your resource file the path to that folder. Then you can use the first method:
var di = new DirectoryInfo(Resources.PPTFolderPath);
foreach(var file in di.GetFiles())
{
var myppnt = ppntApplication.Presentations.Open(fi.FullName);
ppntApplication.Visible = MsoTriState.msoTrue;
[..]
}
But if you really want to store your PPT in the resource file, you can do it like this, with a temporary file for example:
var tmpPath = Path.GetTempFileName();
try
{
File.WriteAllBytes(tmpPath, Resources.sendToPPTTemp);
var myppnt = ppntApplication.Presentations.Open(tmpPath);
ppntApplication.Visible = MsoTriState.msoTrue;
[..]
}
finally
{
// you have to delete your tmp file at the end!!!
// probably not the better way to do it because I guess the program does not block on Open.
// Better store the file path into a list and delete later.
var fi = new FileInfo(tmpPath);
fi.Delete();
}
I'm using an EPi server provider:
<add virtualPath="~/WorkplaceFiles/" physicalPath="C:\Temp Files\Workplaces"
name="workplaceFiles" type="EPiServer.Web.Hosting.VirtualPathNativeProvider,EPiServer"
showInFileManager="true" virtualName="workplaceUploadDocuments" bypassAccessCheck="true" maxVersions="5" />
Here's the defination for the provider:
VirtualPathUnifiedProvider provider =
VirtualPathHandler.GetProvider(DocumentConstants.WorkplaceFiles) as VirtualPathUnifiedProvider;
And here comes my problem - if I define a string for example like this:
string path = "2999/Documents/document.txt"
path = String.Concat(provider.VirtualPathRoot, path);
FileInfo file = new FileInfo(path);
FileInfo won't be able to find this file, because it's using the virtualPath not the physicalPath.
How can I take the physicalPath, so that I will be able to find the file with FileInfo?
// When I'm on this line I would like my path string to be "C:\Temp Files\Workplaces\2999\Documents\document.txt"
FileInfo file = new FileInfo(path);
Reading the question again, the proper method seems to be VirtualPathUnifiedProvider.TryGetHandledAbsolutePath
With it, you'd do something like this:
string path;
provider.TryGetHandledAbsolutePath("2999/Documents/document.txt", out path);
FileInfo file = new FileInfo(path);
This is what you could do (if you only know the name of the VPP provider):
const string path = "Testbilder/startsidan_896x240.jpg";
var provider = VirtualPathHandler.GetProvider("SiteGlobalFiles") as VirtualPathUnifiedProvider;
if (provider != null)
{
var virtualPath = VirtualPathUtilityEx.Combine(provider.VirtualPathRoot, path);
var file = VirtualPathHandler.Instance.GetFile(virtualPath, true) as UnifiedFile;
if (file != null)
{
var fileInfo = new FileInfo(file.LocalPath);
}
}
If you already know the full virtual path of the file, you can go directly to VirtualPathHandler.Instance.GetFile(...).
The namespaces you need are EPiServer.Web and EPiServer.Web.Hosting (and System.IO).
I have the code below and I get the result like this
C:\\Users\\Administrator\\Projects\\CA\\Libraries\\ConvertApi-DotNet\\Example\\word2pdf-console\\bin\\Release\\\\..\\..\\..\\..\\test-files\\test.docx
The file is found but I would like to show user this path and the formating is not user friendly. I would like to get
C:\\Users\\Administrator\\Projects\\CA\\Libraries\\test-files\\test.docx
I have tried to use Path.Combine but it do not work.
var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
string inFile = baseDirectory + #"\..\..\..\..\test-files\test.docx";
You could use a combination of Path.Combine and Path.GetFullPath:
var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
var file = #"..\..\..\..\test-files\test.docx";
string inFile = Path.GetFullPath(Path.Combine(baseDirectory, file));
Description
You say that the file is found.
Then you can use FileInfo (namespace System.IO) for that.
Sample
FileInfo f = new FileInfo(fileName);
f.Exists // Gets a value indicating whether a file exists.
f.DirectoryName // Gets a string representing the directory's full path.
f.FullName // Gets the full path of the directory or file.
More Information
MSDN - FileInfo Class