I have an XmlTextReader to read series of XML files to load some information in to my program.
However, in some XML files I have the file name of an image and I want to load that image.
But the problem is the XML file does not have the full path of the image.
<Image id="ImageId" File="Image.bmp" />
<!-- full path is not available. Image is behind XML-->
This means the Image exist where the xml file exists.
for some reason, the only way to get the path of the XML file is to get the path of the XmlTextReader reading the current XML file.
I did some research and I found out you can retrieve the XML path from the XmlTextReader as below:
string path = reader.BaseURI; // this will get the path of reading XML
// reader is XmlTextReader
How can I combine path with the image's path?
I have tried the following way:
string FullImagePath = Path.Combine(reader.BaseURI, imagePath);
These are the values of the variables:
reader.BaseURI is "file:///D:/.../currentXml.xml"
imagePath is "Image.bmp".
Finally, FullImagePath, after assigning the result of Path.Combine is file:///D:/.../currentXml.xml\\Image.bmp, which is not what I expect.
Expected path of the image is: D:/.../Image.bmp, in the same directory as currentXml.xml.
So how can I get the path of the image file?
You have a two different problems that you need to solve separately.
Depending on the API used to consume the image file, a file:// URI path may or may not be supported. So you'd want to make that a local path as explained in Convert file path to a file URI?:
string xmlPath = "file://C:/Temp/Foo.xml";
var xmlUri = new Uri(xmlPath); // Throws if the path is not in a valid format.
string xmlLocalPath = xmlUri.LocalPath; // C:\Temp\Foo.xml
Then you want to build the path to the image file, which resides in the same directory as the XML file.
One way to do that is to get the directory that file is in, see Getting the folder name from a path:
string xmlDirectory = Path.GetDirectoryName(xmlLocalPath); // C:\Temp
Then you can add your image's filename:
string imagePath = Path.Combine(xmlDirectory, "image.png"); // C:\Temp\image.png
Or, in "one" line:
string imagePath = Path.Combine(Path.GetDirectoryName(new Uri(reader.BaseURI).LocalPath),
ImagePath);
Path.Combine(Path.DirectoryName(reader.BaseUri), imagePath)
As you are dealing with resolving URLs I would suggest to use XmlUrlResolver in System.Xml:
string localPath = new XmlUrlResolver().ResolveUri(new Uri(baseUri), imageName).LocalPath;
Related
I have uploaded my file to my website with a random name. Now I want to get the original file name.
I have tried to get the file name:
var dllUrl = "https://cdn.example.com/c6244c971f.dll";
FileVersionInfo myFileVersionInfo = FileVersionInfo.GetVersionInfo(dllUrl);
Console.WriteLine(myFileVersionInfo.OriginalFilename);
but it did not work.
How can I get the original name from the version resource?
The parameter of FileVersionInfo.GetVersionInfo is a file name, not a URL.
You need to download the file (see e.g. here) to a temporary file and then use FileVersionInfo.GetVersionInfo(temporaryFile).
There is no other was to do this, because the original file name is not encoded in the URL nor is there a HTTP verb (or any other standardized way) to get only the version resource of a file.
I agree with Klaus Gütter. You need to download the file.
Here is the code:
var uri = "https://cdn.example.com/c6244c971f.dll";
var uniqueFileName = Path.GetRandomFileName();
var uniqueFilePath = Path.Combine(#"D:\temp", uniqueFileName);
// Download the file
new WebClient().DownloadFile(uri, uniqueFilePath);
// Get file version info
FileVersionInfo myFileVersionInfo = FileVersionInfo.GetVersionInfo(uniqueFilePath);
Console.WriteLine(myFileVersionInfo.OriginalFilename);
// Delete the file from local disk
File.Delete(uniqueFilePath);
I already know how to browse for an image using open file dialog. So let's say we already got the path :
string imagePath = "Desktop/Images/SampleImage.jpg";
I want to copy that file, into my application folder :
string appFolderPath = "SampleApp/Images/";
How to copy the given image to the appFolderPath programmatically?
Thank you.
You could do something like this:
var path = Path.Combine(
System.AppDomain.CurrentDomain.BaseDirectory,
"Images",
fileName);
File.Copy(imagePath, path);
where fileName is the actual name of the file only (including the extension).
UPDATE: the Path.Combine method will cleanly combine strings into a well-formed path. For example, if one of the strings does have a backslash and the other doesn't it won't matter; they are combined appropriately.
The System.AppDomain.CurrentDomain.BaseDirectory, per MSDN, does the following:
Gets the base directory that the assembly resolver uses to probe for assemblies.
That's going to be the executable path you're running in; so the path in the end (and let's assume fileName is test.txt) would be:
{path_to_exe}\Images\test.txt
string path="Source imagepath";
File.Copy(System.AppDomain.CurrentDomain.BaseDirectory+"\\Images", path);
\ System.AppDomain.CurrentDomain.BaseDirectory is to provide path of the application folder
ok, i found this on internet to upload some files.
if (FileUpload1.HasFile)
{
//create the path to save the file to
string fileName = Path.Combine(#"E:\Project\Folders", FileUpload1.FileName);
//save the file to our local path
FileUpload1.SaveAs(fileName);
}
and this
//check to make sure a file is selected
if (FileUpload1.HasFile)
{
//create the path to save the file to
string fileName = Path.Combine(Server.MapPath("~/Files"), FileUpload1.FileName);
//save the file to our local path
FileUpload1.SaveAs(fileName);
}
what is the difference, which one to use? i got confuse. by the way, if i can store file path in database, and next time when i want to delete or see that file, how can i retrieve that? so let say, first i add a record to database and uploaded a .doc file / excel file, next time when i want to edit that record, i want to retrieve the uploaded file, and show it in UI. thanks.
use second one cause it will convert relative or virtual path to real path itself . .u should get path from db and use it to resolve the path the same way you are storing and do manipulation on it delete and etc. for displaying url="~/Files/yourfilename"
yourfilefromdb -u retrieve it from db
string filepath = Path.Combine(Server.MapPath("~/Files"), yourfilefromdb);
File.Delete(filepath);
for showing
if it accessible directly u can just write url="~/Files/yourfilefromdb"
The only difference in two code blocks posted you is in specifying file path.
In case 1, static location is specified to save the file. It can cause problem, if location to save files differ in your production environment. It will require rebuild in that case.
While, in case 2, location is specified using relative path. So, it will always save files at "/Files" location.
//if you already know your folder is: E:\ABC\A then you do not need to use Server.MapPath, this last one is needed if you only have a relative virtual path like ~/ABC/A and you want to know the real path in the disk...
if (FileUpload1.HasFile)
{
string fileName = Path.Combine(#"E:\Project\Folders", FileUpload1.FileName);// they know the right path so .they using directly
FileUpload1.SaveAs(fileName);
}
if (FileUpload1.HasFile)
{
string fileName = Path.Combine(Server.MapPath("~/Files"), FileUpload1.FileName);// i don't know path is correct or not so they using Server.MapPath. . .
FileUpload1.SaveAs(fileName);
}
I found I could get a file by:
var files = System.IO.Directory.GetFiles("Some Directory");
The file is one contained within this collection;
However is there a method to get a single file by passing the file path tothis method?
There are alot of ways to directly access a file by path. Here are a few:
string path = // path string here
File.ReadAllText(path);
File.OpenRead(path);
File.OpenWrite(path);
Essentially everything the 'File' class does is related to a single file. Its a static class in the System.IO namespace.
http://msdn.microsoft.com/en-us/library/system.io.file.aspx
http://msdn.microsoft.com/en-us/library/b9skfh7s.aspx
System.IO.File.Open
StreamReader content1 = File.OpenText("../DATA/heading.txt");
I have a txt file in a subfolder called DATA, I am trying to access this file from code but the code goes to the .net runtime directitory and not the application directory, thanks for the help
string filePath = Server.MapPath("/Data/heading.txt");
StreamReader content1 = File.OpenText(filePath);
Try using the Application's Entry assembly to get your text file path like this.
Assembly asm = Assembly.GetEntryAssembly();
string appDir = Path.GetDirectoryName(asm.Location);
string filePath = Path.Combine(appDir, "../DATA/heading.txt");
StreamReader content1 = File.OpenText(filePath);
This will work for any application that starts as an exe.
Since you marked this as asp.net are you looking on the server from asp.net? If so try Server.MapPath http://msdn.microsoft.com/en-us/library/ms524632(v=vs.90).aspx
From MSDN - http://msdn.microsoft.com/en-us/library/system.io.file.opentext.aspx
The path parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see GetCurrentDirectory.
http://msdn.microsoft.com/en-us/library/system.io.directory.getcurrentdirectory.aspx
So your current directory is not set to your application directory.