Create new version of file programmatically

Vote:
 

Hi,

 

I'm adding files to a custom vpp folder which uses the default VirtualPathNonUnifiedProvider:

var pageRootDirectory = (UnifiedDirectory)GenericHostingEnvironment.VirtualPathProvider.GetDirectory("~/CatalogImages/");
var versioningDirectory = pageRootDirectory as VersioningDirectory;
VersioningFile versioningFile = (VersioningFile) pageRootDirectory.CreateFile(resizedFileName);

I thought it whould always create a new version of a file when I use the create file but it doesn't, because the second time I create the same file it will throw an exception. 

My question is how do I create a new version of a file?

Thanks in advanced,

Jeroen Slor

 

#61725
Sep 28, 2012 18:10
Vote:
 

Hi,

The VPP needs to be a VirtualPathVersioningProvider. You can check that in EPiServer.config. And this code should work:

UnifiedDirectory unifiedDirectory = HostingEnvironment.VirtualPathProvider.GetDirectory(path) as UnifiedDirectory;

UnifiedFile unifiedFile = HostingEnvironment.VirtualPathProvider.FileExists(filePath)
                                ? HostingEnvironment.VirtualPathProvider.GetFile(filePath) as UnifiedFile
                                : unifiedDirectory.CreateFile(filePath);

using (Stream stream = unifiedFile.Open(FileMode.OpenOrCreate, FileAccess.Write))
{
    // Write to the stream
}

    

#61727
Sep 29, 2012 0:11
Vote:
 

Hi,

 

Thanks for the quick reply. What I whould like to achieve is if the file already exists, that I can create a new version of this file. How can I do this?

 

Thanks!

Jeroen

#61730
Sep 29, 2012 11:36
Vote:
 

If you're using a VirtualPathVersioningProvider, there will be a new version of the file, if it exists already.

#61732
Sep 30, 2012 14:48
Vote:
 

So on the moment I see that the file already exists and I use the GetFile method I get a new version of this file? Don't I have to manualy create one? How do I save the new version of this file without overwriting the current.

 

Thanks in advanced,

 

Jeroen

#61733
Sep 30, 2012 17:30
Vote:
 

No you don't get a new version, but one will be created when you write to the stream. You don't have to do more than write to stream, it just works magically.

#61734
Sep 30, 2012 17:36
Vote:
 

Ah ok it's getting clear for me thanks! I'll give it a shot tomorrow and let you know.

#61735
Sep 30, 2012 19:45
This topic was created over six months ago and has been resolved. If you have a similar question, please create a new topic and refer to this one.
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.