Setting image source to application folder - c#

I'm trying to get an image from a certain path, but the path must only be referenced from the application's current folder and not from the Local C: drive.
My reason for this is because the application is going to get published soon and I can't reference the image to the same local location on my current PC, because the application is going to be used on a lot of other PC's and the path would not work on other someone else's computer.
This is the current path that works:
SetDefaultImage(new Binary(File.ReadAllBytes("C:\\Users\\mclaasse\\Desktop\\Haze Update\\Haze\\Haze\\Icons\\user6.jpg")));
And this is how I need it to be:
SetDefaultImage(new Binary(File.ReadAllBytes("Haze\\Icons\\user6.jpg")));
But i'm getting the error:
Could not find a part of the path 'C:\Haze\Icons\user6.jpg'.
Is there a simple work around for getting my path to work?

Not sure if this is exactly what you need, but provided that you have an image file user6.jpg in your Visual Studio project in a project folder named Images, and the Build Action of the image file is set to Resource, you could simply load it from a Resource File Pack URI:
var image = new BitmapImage(new Uri("pack://application:,,,/Images/user6.jpg"));

None of the references worked for me(I don't know why), but this worked:
string directory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
string filePath = Path.Combine(directory, "Icons\\user6.jpg");
Then check if the file that you are looking for exists:
if (!File.Exists(filePath))
{
MessageBox.Show("The default image does not exist", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
else
{
...
}

Related

C# shell.NameSpace does not find the folder on an external device

I have the following problem:
I am using the Shell32 library to be able to access files even on external devices such as my android phone. Getting a local folder and the Phone itself works, but not the folder on the phone. My current code to get a folder (found the solution here):
Shell shell = new Shell();
Folder folder = shell.BrowseForFolder((int)Hwnd, "Choose Folder", 0, 0);
if (folder != null) {
FolderItem fi = (folder as Folder3).Self;
string path = fi.Path;
//...
}
And later I am trying to get the Folder again by using:
Folder folder = shell.NameSpace(path);
which works fine for all local files and the phone itself, but not for the directories on the phone.
The path for a local directory looks like a normal path: "D:\\Bilder\\Bretagne 2016",
the one for the phone:
"::{20D04FE0-3AEA-1069-A2D8-08002B30309D}\\\\\\?\\usb#vid_04e8&pid_6860&ms_comp_mtp&samsung_android#6&2a1f2d33&0&0000#{6ac27878-a6fa-4155-ba85-f98f491d4f33}",
which is some identifier, but works and then for a specific directory on my phone:
"::{20D04FE0-3AEA-1069-A2D8-08002B30309D}\\\\\\?\\usb#vid_04e8&pid_6860&ms_comp_mtp&samsung_android#6&2a1f2d33&0&0000#{6ac27878-a6fa-4155-ba85-f98f491d4f33}\\SID-{10001,SECZ9519043CHOHB,114301988864}\\{E398106A-CD20-9A9C-490B-5079C2D70B84}"
with this path I just get a null object when calling shell.NameSpace(path);
Has anyone an idea what I am doing wrong? Have absolutely no idea how to fix this.
Thanks in advance,
Finn
So, found an interesting workaround.
To get a folder on my phone, I can just join the id/path I get from selecting the phone in the BrowseForFolder dialog and the human readable path like this:
::{20D04FE0-3AEA-1069-A2D8-08002B30309D}\\\\\\?\\usb#vid_04e8&pid_6860&ms_comp_mtp&samsung_android#6&2a1f2d33&0&0000#{6ac27878-a6fa-4155-ba85-f98f491d4f33}\\Phone\DCIM\Camera and everything works fine.
Not really an idea why the path you get from Folder.path does not work, but this does. As long as there is no other solution this works at least.

a file cannot be deleted and copy and move do not work in C# VS2013

I am trying to copy a file in same folder from C# VS2013 on win7.
string myFile = #"C:\Temp\MyFile.txt"
if (File.Exists(myFile))
{
File.Delete(myFile);
}
File.Move(myFileSource, myFile);
I got error:
Additional information: Cannot create a file when that file already exists.
I checked the folder and found that the file "myFile.txt" is still there after deleting.
If i used:
File.Copy(myFileSource, myFile, true);
Error:
Additional information: Access to the path 'C:\Temp\myFile.txt' is denied.
Why ? thanks
Run visual studio as administrator. It's likely a security issue related to UAC.
You may also want to consider writing the file to somewhere where is will work for all such as:
string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);

File already exists exception file.copy

I am trying to copy a driver file from my application folder to driver folder in windows 7. But as I run this program File already exists exception has been occurred if I check at driver folder manually the file does not exists at all.
Program.sDriverPath = Path.Combine(Program.sStartUpPath, #"windows7\amd64\MyDriver.sys");
string sPath = sDriverPath;
string sDestPath = Path.Combine(Environment.ExpandEnvironmentVariables(#"%windir%\system32"), #"drivers\MyDriver.sys");
MessageBox.Show("Source " + sDriverPath);
File.Copy(sDriverPath, sDestPath);
If you want to overwrite an existing file you need to use the overload which has a boolean parameter:
public static void Copy(
string sourceFileName,
string destFileName,
bool overwrite)
and specify true for overwrite.
Now it is odd that you say the file doesn't exist in the destination at all - I think it must do, and you're not looking in the right place.
Try setting a breakpoint in your code immediately before you call File.Copy() and check the sDestPath parameter.
I suspect that what is happening is that the File System Redirector is silently redirecting your application to a different folder.
Try checking the folder %windir%\SysWOW64 instead.
Finally, note that the process's user must be running as an administrator to write files into that location.
Thanks #Matthew Watson I found the solution. FSRedirector is redirecting system32 folder to SysWow64 folder.Go to syswow64 folder then go to drives folder you will find your file there.

Could not find a part of the path 'C:\Program Files (x86)\IIS Express\~\TextFiles\ActiveUsers.txt'

I tried many ways to access a text file in my Visual Studio 2012 Solution from a folder named TextFiles
using (System.IO.StreamWriter file = new System.IO.StreamWriter(#"~/TextFiles/ActiveUsers.txt", true))
{
file.WriteLine(model.UserName.ToString());
}
But it kept on throwing the error
Could not find a part of the path 'C:\Program Files (x86)\IIS
Express\~\TextFiles\ActiveUsers.txt'.
Not sure where I made a mistake
You need to use HttpServerUtility.MapPath which will turn the ~/ portion of the path in to the real location it resildes on your hard drive.
So that would change your code to (assuming you are in one of the IIS classes that expose a Server property to it's methods)
var path = Server.MapPath(#"~/TextFiles/ActiveUsers.txt");
using (System.IO.StreamWriter file = new System.IO.StreamWriter(path, true))
{
file.WriteLine(model.UserName.ToString());
}
I ran into a similar issue and ended up using
string sFileName = HttpContext.Current.Server.MapPath(#"~/dirname/readme.txt");
This is an old question but I just ran into this problem myself and wanted to add what I've just discovered, in case it's helpful to anyone else.
If you have UAC turned off but are not running with elevated permissions, and try to write to restricted files (e.g. the "Program Files" folder) you'll get the "could not find a part of the path" error, instead of the (correct) access denied error.
To eliminate the problem, run with elevated permissions as in this solution: https://stackoverflow.com/a/1885543/3838199
~ is not the "user home" or anything else in Windows. You can still set the path as relative to the working directory (where the executable is) by just not specifying a full path.
For .netcore 3.x
You should make use of IWebHostEnvironment using dependency injection.
You can then use it in your code this way
string wwwRootPath = _hostEnvironment.WebRootPath;
string path = Path.Combine(wwwRootPath, $"TextFiles{Path.PathSeparator}ActiveUsers.txt");
Ensure to use PathSeparator otherwise you might face the same error due to the variance in your hosting environment.

Cannot create files on Android with Xamarin

I have a Xamarin-Studio App for Android and I simply want to download files and save them locally. But when I try to create a file in the files folder I get an exception:
File.Create("data/data/com.company.app/files/newFile.png");
gives me:
System.UnauthorizedAccessException
Access to the path 'data/data/com.company.app/files/newFile.png' is denied.
What am I doing wrong?
You should use Environment or IsolatedStorage. For example:
var path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
var filename = Path.Combine(path, "newFile.png");
I am coding Xamarin with VS2013. I had the access denied error for a directory created with the application I am writing. My application creates a directory called /storage/emulated/0/POIApp by concatenating via:
System.IO.Path.Combine(Android.OS.Environment.ExternalStorageDirectory.Path, "POIApp");
I found that I had to use VS2013 to edit the "properties" of my application (POIApp), i.e., right-click the project icon in the solution explorer; choose properties from the pop-up menu. A new tab appears in the main VS2013 window. On the left there are a few choices, e.g., Application, Android Manifest, Android Options, Build, etc. Choose "Android Manifest". At the bottom of the main panel is a section "required permissions". My problem was solved when I checked "READ_EXTERNAL_STORAGE" and "WRITE_EXTERNAL_STORAGE".
Add the following permission to Android.Manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I finally realized that File.create() was not the problem. I had code like this:
string tmpFilePath = FilesDir.AbsolutePath.stringByAppendingPath (f.Path);
Java.IO.File tmpFile = new Java.IO.File( tmpFilePath);
tmpFile.Mkdirs ();
Yet, Mkdirs() does not only create all intermediate directories – as I had assumed – but also creates a directory at the file path itself. So the file could not be created because there already was a directory with the same name.
The correct way is:
string tmpFile = FilesDir.AbsolutePath.stringByAppendingPath (f.Path);
Java.IO.File tmpParentFolder = new Java.IO.File(tmpFile).getParentFile();
tmpParentFolder.Mkdirs ();
In my defense, an FileExistsAndIsDirectory exception would have been much more helpful than the UnauthorizedAccessException
Using Mono, I think must be the same as in Xamarin Studio.
var path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
File.Create(path + "newFile.png");

Categories