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).
Related
i'm trying to save multiple images with File.WriteAllBytes(), even after i tried to seperate between the saves with 'Thread.Sleep()' it's not working..
my code:
byte[] signatureBytes = Convert.FromBase64String(model.Signature);
byte[] idBytes = Convert.FromBase64String(model.IdCapture);
//Saving the images as PNG extension.
FileManager.SaveFile(signatureBytes, dirName, directoryPath, signatureFileName);
FileManager.SaveFile(idBytes, dirName, directoryPath, captureFileName);
SaveFile Function:
public static void SaveFile(byte[] imageBytes, string dirName, string path, string fileName, string fileExt = "jpg")
{
if (!string.IsNullOrEmpty(dirName)
&& !string.IsNullOrEmpty(path)
&& !string.IsNullOrEmpty(fileName)
&& imageBytes.Length > 0)
{
var dirPath = Path.Combine(path, dirName);
var di = new DirectoryInfo(dirPath);
if (!di.Exists)
di.Create();
if (di.Exists)
{
File.WriteAllBytes(dirPath + $#"\{fileName}.{fileExt}", imageBytes);
}
}
else
throw new Exception("File cannot be created, one of the parameters are null or empty.");
}
File.WriteAllBytes():
"Creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten"
As expecify in :
https://msdn.microsoft.com/en-ca/library/system.io.file.writeallbytes(v=vs.110).aspx
So if you can only see the last one, you are overwriting the file.
Apart from the possibility (as mentioned by #Daniel) that you're overwriting the same file, I'm not sure about this code:
var di = new DirectoryInfo(dirPath);
if (!di.Exists)
di.Create();
if (di.Exists)
{
...
}
I'd be surprised if, having called di.Create(), the Exists property is updated. In fact, it is not updated - I checked.
So, if the directory did not exist, then you won't enter the conditional part even after creating the directory. Could that explain your issue?
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);
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
I am working on a project where I want to copy some files in one directory to a second already existing directory.
I can't find a way to simply copy from one folder to another. I can find copy file to a new file, or directory to a new directory.
The way I have my program set up right now is I copy the file and leave it in same directory, then move that copy to the directory that I want.
Edit:
Thanks everyone. All of your answers worked. I realized what I did wrong, when i set the destination path I didn't add a filename. Everything works now, Thanks for the super speedy responses.
string fileToCopy = "c:\\myFolder\\myFile.txt";
string destinationDirectory = "c:\\myDestinationFolder\\";
File.Copy(fileToCopy, destinationDirectory + Path.GetFileName(fileToCopy));
File.Copy(#"someDirectory\someFile.txt", #"otherDirectory\someFile.txt");
works fine.
MSDN File.Copy
var fileName = "sourceFile.txt";
var source = Path.Combine(Environment.CurrentDirectory, fileName);
var destination = Path.Combine(destinationFolder, fileName);
File.Copy(source, destination);
Maybe
File.Copy("c:\\myFolder\\myFile.txt", "c:\\NewFolder\\myFile.txt");
?
This worked for me:
string picturesFile = #"D:\pictures";
string destFile = #"C:\Temp\tempFolder\";
string[] files = Directory.GetFiles(picturesFile);
foreach (var item in files)
{
File.Copy(item, destFile + Path.GetFileName(item));
}
I used this code and it work for me
//I declare first my variables
string sourcePath = #"Z:\SourceLocation";
string targetPath = #"Z:\TargetLocation";
string destFile = Path.Combine(targetPath, fileName);
string sourceFile = Path.Combine(sourcePath, fileName);
// To copy a folder's contents to a new location:
// Create a new target folder, if necessary.
if (!Directory.Exists(targetPath))
{
Directory.CreateDirectory(targetPath);
}
// To copy a file to another location and
// overwrite the destination file if it already exists.
File.Copy(sourceFile, destFile, true);
If the destination directory doesn't exist, File.Copy will throw. This version solves that
public void Copy(
string sourceFilePath,
string destinationFilePath,
string destinationFileName = null)
{
if (string.IsNullOrWhiteSpace(sourceFilePath))
throw new ArgumentException("sourceFilePath cannot be null or whitespace.", nameof(sourceFilePath));
if (string.IsNullOrWhiteSpace(destinationFilePath))
throw new ArgumentException("destinationFilePath cannot be null or whitespace.", nameof(destinationFilePath));
var targetDirectoryInfo = new DirectoryInfo(destinationFilePath);
//this creates all the sub directories too
if (!targetDirectoryInfo.Exists)
targetDirectoryInfo.Create();
var fileName = string.IsNullOrWhiteSpace(destinationFileName)
? Path.GetFileName(sourceFilePath)
: destinationFileName;
File.Copy(sourceFilePath, Path.Combine(destinationFilePath, fileName));
}
Tested on .NET Core 2.1
NET6 - Extension method
[DebuggerStepThrough]
public static FileInfo CopyToDir(this FileInfo srcFile, string destDir) =>
(srcFile == null || !srcFile.Exists) ? throw new ArgumentException($"The specified source file [{srcFile.FullName}] does not exist", nameof(srcFile)) :
(destDir == null || !Directory.Exists(destDir)) ? throw new ArgumentException($"The specified destination directory [{destDir}] does not exist", nameof(destDir)) :
srcFile.CopyTo(Path.Combine(destDir, srcFile.Name), true);
I was just wondering when you have for example:
var dir = new DirectoryInfo(#"C:\Temp");
Is there an easier/clearer way to add a new file to that directory than this?
var file = new FileInfo(Path.Combine(dir.FullName, "file.ext"));
I'm thinking I can probably just make an extension method or something, but curious if something already exists that can't see here... I mean the DirectoryInfo does have GetFiles() method for example.
What is it that you want to do? The title says "Creating a new file". A FileInfo object is not a file; it's an object holding information about a file (that may or may not exist). If you actually want to create the file, there are a number of ways of doing so. One of the simplest ways would be this:
File.WriteAllText(Path.Combine(dir.FullName, "file.ext"), "some text");
If you want to create the file based on the FileInfo object instead, you can use the following approach:
var dir = new DirectoryInfo(#"C:\Temp");
var file = new FileInfo(Path.Combine(dir.FullName, "file.ext"));
if (!file.Exists) // you may not want to overwrite existing files
{
using (Stream stream = file.OpenWrite())
using (StreamWriter writer = new StreamWriter(stream))
{
writer.Write("some text");
}
}
As a side note: it is dir.FullName, not dir.FullPath.
Why don't you use:
File.Create(#"C:\Temp\file.ext");
or
var dir = new DirectoryInfo(#"C:\Temp");
File.Create(dir.FullName + "\\file.ext");
While there does exist Directorynfo.GetFiles() methods, they only return files that actually exist on disk. Path.Combine is about hypothetical paths.
Try these extension methods:
public static FileInfo CombineWithFileName(this DirectoryInfo directoryInfo, string fileName)
{
return new FileInfo(Path.Combine(directoryInfo.Name, fileName));
}
public static DirectoryInfo CombineWithDirectoryName(this DirectoryInfo directoryInfo, string directoryName)
{
return new DirectoryInfo(Path.Combine(directoryInfo.Name, directoryName));
}