I have this code in my controller:
public ActionResult Upload(ScormUploadViewModel model)
{
if (ModelState.IsValid)
{
if (model.ScormPackageFile != null)
{
string zipCurFile = model.ScormPackageFile.FileName;
string destinationDirectoryName = Path.GetFullPath(zipCurFile);
//.GetFileNameWithoutExtension(zipCurFile);
Directory.CreateDirectory(destinationDirectoryName);
}
}
}
I upload a zip file through my view and then need to unzip it in the same location in a folder with the same name as the zipfilename
the file is: C:\TFSPreview\Zinc\Web\Project\ScormPackages\Windows 8 Training SkyDrive - Spanish.zip
I need to create a folder in C:\TFSPreview\Zinc\Web\Project\ScormPackages\
with the name: Windows 8 Training SkyDrive - Spanish
thus have: C:\TFSPreview\Zinc\Web\Project\ScormPackages\Windows 8 Training SkyDrive - Spanish\
and UNZIP in this above folder all the files contained in C:\TFSPreview\Zinc\Web\Project\ScormPackages\Windows 8 Training SkyDrive - Spanish.zip
so my question is: will CreateDirectory() create the folder Windows 8 Training SkyDrive - Spanish in C:\TFSPreview\Zinc\Web\Project\ScormPackages\ or will it try and create the folder in just c:??
thanks
It will create the directory inside C:\TFSPreview\Zinc\Web\Project\ScormPackages\. In fact, it will create all directories in that path if they don't already exist:
Any and all directories specified in path are created, unless they
already exist or unless some part of path is invalid. The path
parameter specifies a directory path, not a file path. If the
directory already exists, this method does not create a new directory,
but it returns a DirectoryInfo object for the existing directory.
However, this code has a bug: destinationDirectoryName is not the path to a directory, it's a path to a file inside the destination directory. So what you should be doing is
// zipCurFile = C:\...\ScormPackages\Windows 8 Training SkyDrive - Spanish.zip
// Path.GetDirectoryName gives "C:\...\ScormPackages"
// Path.GetFileName gives "Windows 8 Training SkyDrive - Spanish"
// Path.Combine on these two gives you the correct target
Directory.CreateDirectory(
Path.Combine(
Path.GetDirectoryName(zipCurFile), Path.GetFileName(zipCurFile));
Related
I have multiple folders in a single directory and each folder(folder name as per Siteid) contains the .orig file. so I want to copy the latest file created ".orig" file from multiple directories into a single directory.
The file received from ftp in each directory on a weekly basis
Filename format
:PSAN{SiteId}_20190312_TO_20190318_AT_201903191600.txt
I tried to copy a file using windows command
for /R "source" %f in (*.orig) do copy %f "destination"
using this command I able to copy an all .orig file from multiple folders into a single folder but it fetches all file.
can we do modification in command to fetch the latest file?
How to perform this task using an SSIS package or using cmd.
Create two package variables called InputFileNameWithPath and OutputFolderPath. The Former will be dynamically set in the package. The former should be hardcoded to your destination folder name.
Create a ForEachLoop enumerator of type File Enumerator. Set the path to the root folder and select the check box for traverse sub-folders. You may want to add an expression for the FileMask and set it to *.orig that way only the .orig files are moved (assuming there are other files in the directory that you do not want to move) Assign the fully qualified path to the package variable InputFileName.
Then add a System File Task into the ForEachLoop enumerator and have it move the file. from the InputFileNameWithPath to the OutputFolderPath.
You can use a Script Task to achieve that, you can simply store the folders within an array, loop over these folders get the latest file created and copy it to the destination directory (you can achieve this without SSIS), as example:
using System.Linq;
string[] sourcefolders = new string[] { #"C:\New Folder1", #"C:\New Folder2" };
string destinationfolder = #"D:\Destination";
foreach (string srcFolder in sourcefolders)
{
string latestfile = System.IO.Directory.GetFiles(srcFolder, "*.orig").OrderByDescending(x => System.IO.File.GetLastWriteTime(x)).FirstOrDefault();
if (!String.IsNullOrWhiteSpace(latestfile))
{
System.IO.File.Copy(latestfile, System.IO.Path.Combine(destinationfolder, System.IO.Path.GetFileName(latestfile)));
}
}
An example C# Script Task for this is below. This uses SSIS variables for the source and destination folders, and make sure to add these in the ReadOnlyVariables field if that's how you're storing them. Be sure that you have the references listed below as well. As noted below, if a file with the same name exists it will be overwritten to avoid such an error, however I'd recommend confirming that this meets your requirements. The third parameter of File.Copy controls this, and can be omitted as it's not a required parameter.
using System.Linq;
using System.IO;
using System.Collections.Generic;
string sourceFolder = Dts.Variables["User::SourceDirectory"].Value.ToString();
string destinationFolder = Dts.Variables["User::DestinationDirectory"].Value.ToString();
Dictionary<string, string> files = new Dictionary<string, string>();
DirectoryInfo sourceDirectoryInfo = new DirectoryInfo(sourceFolder);
foreach (DirectoryInfo di in sourceDirectoryInfo.EnumerateDirectories())
{
//get most recently created .orig file
FileInfo fi = di.EnumerateFiles().Where(e => e.Extension == ".orig")
.OrderByDescending(f => f.CreationTime).First();
//add the full file path (FullName) as the key
//and the name only (Name) as the value
files.Add(fi.FullName, fi.Name);
}
foreach (var v in files)
{
//copy using key (full path) to destination folder
//by combining destination folder path with the file name
//true- overwrite file if file by same name exists
File.Copy(v.Key, destinationFolder + v.Value, true);
}
I want to access a folder in which I can save temporary files and write there a file and where I don't need permission to write to the folder.
I currently use:
string targetBaseDir = Environment.GetFolderPath(
Environment.SpecialFolder.Personal,
Environment.SpecialFolderOption.Create
);
This gives me a private directory for which I need no permissions which is the directory that corresponds to Context.getFilesDir(), however as I don't need the file to exist permanently it would be cleaner if I could save them in the directory that corresponds to Context.getFilesDir(). What do I have to write instead of .Personal to get the directory?
You can use FileSystem.AppDataDirectory via Xamarin.Essentials in your .NetStd library to obtain what is the "getFilesDir()" location on Android.
Example:
var appData = Xamarin.Essentials.FileSystem.AppDataDirectory;
appData equals /data/user/0/com.sushihangover.FormsTestSuite/files
And the Android FilesDir:
Log.Debug("SO", FilesDir.ToString() );
Equals /data/user/0/com.sushihangover.FormsTestSuite/files
access a folder in which I can save temporary files
In that case use the Cache dir:
var cacheDir = Xamarin.Essentials.FileSystem.CacheDirectory;
cacheDir would equal: `/data/user/0/com.sushihangover.FormsTestSuite/cache
re: https://learn.microsoft.com/en-us/xamarin/essentials/
Both Environment.SpecialFolder.Personal and Environment.SpecialFolder.MyDocuments will give you the path of Context.getFilesDir().
However, if you want to save small temporary files, you can make use of the cache directory Context.getCacheDir().
There is no special folder enum for the cache directory though. You'll have to get the path from the current context Context.CacheDir.Path, or from Xamarin.Essentials.FileSystem.CacheDirectory if you use Xamarin.Essentials API.
Read more:
File access with Xamarin.Android with SpecialFolder
Writing cache file in internal storage
File system helpers in Xamarin.Essentials
how can the name of a folder and names of all the sub folders within that folder be fetched.
For example if we upload a file and as say
$file->getClientOriginalName();
and it gets the name of the file as it is stored in the device similarly
Is there any method which returns the full directory of the folder or the path of files stored within that folder?
I am making Windows 8.1 Universal App and want to retrieve file,
(local -> folder -> sub Folder -> file) which is stored in Local Folder.
One way is open Local Folder, then open folder, then open sub folder, then file.
But If I know the path, can I simply open the file?
(Like in Windows Phone 8, store.OpenFile())
Is there an API which would return Storage File when passed path?
Example: GetStorageFile("local/folder/subFolder/file") ?
You can use StorageFile.GetFileFromApplicationUriAsync and pass in a URI such as ms-appdata:///local/folder/subfolder/file.txt. This is preferred over GetFileFromPathAsync (#Parad1s3's suggestion) since it is relative to your data folder and won't change if the location of the app changes (eg, on a phone the user can move to or from the SD card).
string path = ApplicationData.Current.LocalFolder + "\\" + "YourFolder" + "\\" + "YourSubfolder" + "\\yourfile.xml";
StorageFolder folder = ApplicationData.Current.LocalFolder;
StorageFile file = await folder.GetFileAsync(path);
Hope this helps.
I am looking for a way to add File(s) to an existing directory that has a random name as part of a Visual Studio Setup Project and I hoped someone might be able to help me solve this puzzle please.
I have been attempting to obtain the discovered path property of the directory using a Launch Condition; Unfortunately this method returns the full file path including the filename, which cannot be used as a directory property.
The directory in question takes the form [AppDataFolder]Company\Product\aaaaaaaaaaaa\
where aaaaaaaaaaaa is a random installation string.
Within the Launch Condition Setup I check for the directory's existence by searching for a file that would appear inside it,
Search Target Machine
(Name): File marker
Filename: sample.txt
Folder: [AppDataFolder]Company\Product\
Property: DIRFILE
Launch Condition
(Name): File marker exists
Condition: DIRFILE
In the Setup Project I add the file I wish to insert, with the details
Condition: DIRFILE
Folder: 'Installation folder'
Then in File System Setup I add a new folder entry for the random directory aaaaaaaaaaaa
(Name): Installation folder
Condition: DIRFILE
DefaultLocation: [DIRFILE]\..\ *Incorrect*
Property [DIRLOCATION]
As you can see the installer detects the existence of the marker file but, instead of placing my file at the same location, when using [DIRFILE] the installer would incorrectly try and insert it INTO the file;
This is because the file path was returned
[AppDataFolder]Company\Product\aaaaaaaaaaaa\sample.txt
where I instead need the directory path
[AppDataFolder]Company\Product\aaaaaaaaaaaa
Therefore I was wondering if it was possible to return the directory the file was found in from Search Target Machine (as opposed to the file location of the file), if I could extract the directory path by performing a string replace of the filename on the file location DIRFILE within the DefaultLocation field in File System Setup, or if perhaps there is even another method I am missing?
I'm also very interested in a simple solution for this, inside the setup project.
The way I did solve it was to install the files to a temporary location and then copy them to the final location in an AfterInstall event handler. Not a very elegant solution! Since it no longer care about the user selected target path I removed that dialog. Also I needed to take special care when uninstalling.
public override void OnAfterInstall(IDictionary savedState)
{
base.OnAfterInstall(savedState);
// Get original file folder
string originDir = Context.Parameters["targetdir"];
// Get new file folder based on the dir of sample.txt
string newDir = Path.GetDirectoryName(Context.Parameters["dirfile"]);
// Application executable file name
// (or loop for all files on the path instead)
string filename = "ApplicationName.exe";
// Move or copy the file
File.Move(Path.Combine(originDir, filename), Path.Combine(newDir, filename)));
}