Possibility to load video without extension from StreamingAssets? - c#

Is there a way to load video file to video player without specifying the name and extension? Or at least not the extension of the video file.
vp.url = Application.streamingAssetsPath + "/Video/" + "VideoFile.mp4";

No, the url expects an URL or a System path.
The file or HTTP URL that the VideoPlayer reads content from.
File URLs are filesystem paths that are either absolute on the platform or relative to the Player root.
A valid system path includes the extension of a file if it has one.
You could however use Directory.GetFiles in order to find files by partial name in a given folder like
using System.Linq;
using System.IO;
private string FindVideoFile(string folderPath, string partialFileName)
{
if(!Directory.Exists(folderPath)
{
Debug.LogError($"The folder {folderPath} does not exist!", this);
return null;
}
var result = Directory.GetFiles(folderPath, partialFileName + "*", SearchOption.TopDirectoryOnly).FirstOrDefault();
return result;
}
And use it like
var folder = Path.Combine(Application.streamingAssetsPath, "Video");
var fileName = "VideoFile";
var fullPath = FindVideoFile(folder, fileName);
if(!fullPath.IsNullOrWhiteSpace())
{
vp.url = fullPath;
}
else
{
Debug.LogError($"No file called {fileName} was found in folder {folder} ", this);
return;
}
Typed on smartphone but I hope the idea gets clear

Related

How to copy and replace a file for all user profiles with Admin rights

I have researched all the articles here and on Google. While some seem to be what I need I continue to run into this problem. I could certainly use some assistance getting this resolved once and for all.
I want to copy a Customize.xml file from the server and have it replace the current file in all user profiles. I would prefer to make this so that it will run for anyone that logs on each time. Any assistance figuring this out and getting it to work would be greatly appreciated.
using System;
using System.Configuration;
using System.IO;
namespace copy_delete_move_files
{
public class SimpleFileCopy
{
public static object Logger { get; private set; }
static void Main()
{
string fileName = "Customize.xml";
string sourcePath = #"\\serverpath\c$\TestFolder";
string targetPath = #"\\desktoppath\c$\%USERPROFILE%\APPDATA\Roaming\Litera\Customize";
// Use Path class to manipulate file and directory paths.
string sourceFile = Path.Combine(sourcePath, fileName);
string destFile = Path.Combine(targetPath, 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);
// To copy all the files in one directory to another directory.
// Get the files in the source folder.
// Note: Check for target path was performed previously
// in this code example.
if (Directory.Exists(sourcePath))
{
string[] files = Directory.GetFiles(sourcePath);
// Copy the files and overwrite destination files if they already exist.
foreach (string s in files)
{
// Use static Path methods to extract only the file name from the path.
fileName = Path.GetFileName(s);
destFile = Path.Combine(targetPath, fileName);
File.Copy(s, destFile, true);
}
}
else
{
Console.WriteLine("Source path does not exist!");
}
// Keep console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
}

C# mass File renamer

i want to create C# mass file renamer, here is my UI
i have created tes folder, inside of tes there's a file which is 1.txt.
i want to create my program to add prefix and suffix to the files, so 1.txt will become
prefix1suffix
but then i got an error
it's said file already exist though there's only one file on tes folder, which is 1.txt how do i make it work ? where's the error comes from ?
i have tried the following code
private void Rename(string prefix, string filepath, string suffix)
{
//i don't use prefix suffix yet to make sure if my function works
DirectoryInfo d = new DirectoryInfo(filepath);
FileInfo[] file = d.GetFiles();
try
{
foreach (FileInfo f in file )
{
File.Move(f.FullName,"stackoverflow");
}
}
catch (Exception e)
{
cmd.cetakGagal(e.ToString(), title);
}
cmd.cetakSukses("Rename Success", title);
}
and it returns same error as the second picture above.
the following picture is tes folder, there's nothing in tes folder except 1.txt
You are calling File.Move() with a full path for your sourceFileName and a relative path for your destFileName. The relative file path is relative to the current working directory and not to the source file path. I expect that a stackoverflow file exists in the current working directory, most likely created the first time you ran this code.
your File.Move is changing them all to StackOverflow not using the prefix and suffix. If you only have one file in the directory it shouldn't be an issue. Are you sure there is only 1 file?
public static void Move(
string sourceFileName,
string destFileName
)
Looking at this answer might be the clue as you are specifying relative path for the destination file. To obtain the current working directory, see GetCurrentDirectory
The sourceFileName and destFileName arguments are permitted to specify
relative or absolute path information. Relative path information is
interpreted as relative to the current working directory.
You should change
File.Move(f.FullName,"stackoverflow");
to
string fileName = f.Name.Replace(f.Extenstion,string.Empty);
string newFileName = string.Format("{0}{1}{2}",prefix,fileName,suffix);
string newFileWithPath = Path.Combine(f.Directory,newFileName);
if (!File.Exists(newFileWithPath))
{
File.Move(f.FullName,newFileWithPath);
}
The code above will give you that error since, after the first run through, "stackoverflow" exists as a file. Make sure that you check if the destination file exists (using File.Exists) before calling File.Move.
Since your goal is renaming, I would suggest using a test folder filled with files rather than using a piecemeal approach. See if something like this helps:
private void Rename(string prefix, string filepath, string suffix)
{
//i don't use prefix suffix yet to make sure if my function works
DirectoryInfo d = new DirectoryInfo(filepath);
FileInfo[] file = d.GetFiles();
try
{
foreach (FileInfo f in file )
{
f.MoveTo(#filepath + #"\" + prefix + f.Name.Insert(f.Name.LastIndexOf('.'),suffix));
}
}
catch (Exception e)
{
cmd.cetakGagal(e.ToString(), title);
}
cmd.cetakSukses("Rename Success", title);
}
on a side note using a listview to display the filenames and the changes before they're committed will help prevent unwanted changes.

Uploading file to file system

I have seen so many working examples of File uploading with MVC.
However, I want to follow a different approach such that, I want a little abstraction as follows:
I want to introduce a FileService, and inject that to the controller as a dependency. Let the service upload the file and return me a UploadedFile object.
A problem I am having right now is to upload to correct place/directory in file system or application root.
In a controller, I have access to Server object which I can call Server.MapPath and it does the magic, below I cant access to that Object since it is not a Controller.
How can I upload to anywhere in file system or in project root below?
public class FileService : IFileService
{
private const string UploadBase = "/Files";
public File UploadFile(HttpPostedFileBase file)
{
if (file != null)
{
string folder = DateTime.Today.Month + "-" + DateTime.Today.Year;
string finalFolder = Path.Combine(UploadBase, folder);
if (!Directory.Exists(finalFolder))
{
return Directory.CreateDirectory(finalFolder);
}
var filename = UploadFile(file, directoryInfo.Name + "/");
var newFile = new File { ContentType = file.ContentType, FilePath = filename, Filename = file.FileName };
return newFile;
}
return null;
}
An error is :
The SaveAs method is configured to require a rooted path, and the path '9-2013/037a9ddf-7ffe-4131-b223-c4b5435d0fed.JPG' is not rooted.
Re-stating what was noted in comments:
If you want to map the virtual path to the physical path outside of the controller, you can always use HostingEnvironment.MapPath method.

How to set physical path to upload a file in Asp.Net?

I want to upload a file in a physical path such as E:\Project\Folders.
I got the below code by searching in the net.
//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);
}
But in that, I want to give my physical path as I mentioned above. How to do this?
Server.MapPath("~/Files") returns an absolute path based on a folder relative to your application. The leading ~/ tells ASP.Net to look at the root of your application.
To use a folder outside of the application:
//check to make sure a file is selected
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);
}
Of course, you wouldn't hardcode the path in a production application but this should save the file using the absolute path you described.
With regards to locating the file once you have saved it (per comments):
if (FileUpload1.HasFile)
{
string fileName = Path.Combine(#"E:\Project\Folders", FileUpload1.FileName);
FileUpload1.SaveAs(fileName);
FileInfo fileToDownload = new FileInfo( filename );
if (fileToDownload.Exists){
Process.Start(fileToDownload.FullName);
}
else {
MessageBox("File Not Saved!");
return;
}
}
Well,
you can accomplish this by using the VirtualPathUtility
// Fileupload1 is ID of Upload file
if (Fileupload1.HasFile)
{
// Take one variable 'save' for store Destination folder path with file name
var save = Server.MapPath("~/Demo_Images/" + Fileupload1.FileName);
Fileupload1.SaveAs(save);
}

c# open file, path starting with %userprofile%

I have a simple problem. I have a path to a file in user directory that looks like this:
%USERPROFILE%\AppData\Local\MyProg\settings.file
When I try to open it as a file
ostream = new FileStream(fileName, FileMode.Open);
It spits error because it tries to add %userprofile% to the current directory, so it becomes:
C:\Program Files\MyProg\%USERPROFILE%\AppData\Local\MyProg\settings.file
How do I make it recognise that a path starting with %USERPROFILE% is an absolute, not a relative path?
PS: I cannot use
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
Because I need to just open the file by its name. User specifies the name. If user specifies "settings.file", I need to open a file relative to program dir, if user specifies a path starting with %USERPROFILE% or some other thing that converts to C:\something, I need to open it as well!
Use Environment.ExpandEnvironmentVariables on the path before using it.
var pathWithEnv = #"%USERPROFILE%\AppData\Local\MyProg\settings.file";
var filePath = Environment.ExpandEnvironmentVariables(pathWithEnv);
using(ostream = new FileStream(filePath, FileMode.Open))
{
//...
}
Try using ExpandEnvironmentVariables on the path.
Use the Environment.ExpandEnvironmentVariables static method:
string fileName= Environment.ExpandEnvironmentVariables(fileName);
ostream = new FileStream(fileName, FileMode.Open);
I use this in my Utilities library.
using System;
namespace Utilities
{
public static class MyProfile
{
public static string Path(string target)
{
string basePath =
Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) +
#"\Automation\";
return basePath + target;
}
}
}
So I can simply use e.g. "string testBenchPath = MyProfile.Path("TestResults");"
You can use the Environment.Username constant as well. Both of the %USERPROFILE% and this Environment variable points the same( which is the currently logged user). But if you choose this way, you have to concatenate the path by yourself.

Categories

Resources