i want to play the video which name is entered in text box. But it does not play the exact video it plays the first video present in folder. any help please..
Code
String vid_name = data.Text;
string complete_name = vid_name.ToLower() + ".mp4";
string root = System.IO.Path.GetDirectoryName("D:/abc");
string[] supportedExtensions = new[] { ".mp4" };
var files = Directory.GetFiles(Path.Combine(root, "Videos"), "*.*").Where(s => supportedExtensions.Contains(Path.GetExtension(s).ToLower()));
List<VideosDetail> videos = new List<VideosDetail>();
VideosDetail id;
foreach (var file in files)
{
id = new VideosDetail()
{
Path = file,
FileName = Path.GetFileName(file),
Extension = Path.GetExtension(file)
};
FileInfo fi = new FileInfo(file);
id.FileName = fi.Name;
id.Size = fi.Length;
videos.Add(id);
if (id.FileName == complete_name)
{
VideoList.ItemsSource = videos; //**Problem comes here
}
else
{
MessageBox.Show("no such video is available. ");
}
}
Since videos is a List, the line
VideoList.ItemsSource = videos;
Points to all the videos in the folder (up to the one that actually matches the filename you entered). Hence, the unwanted result.
You should probably pass the index of the video in your list, something like:
player.Source = videos[x];
Hope this helps!
Related
I wrote a function that when user clicks on button for pdf, user will only show the pdf documents. I'm having a difficulty about where to put returns in this function.
public IActionResult GetFiles(string dir) {
if ((dir == null) || (!Directory.Exists(dir))) { return BadRequest(); }
var filesList = new List<FileImage>();
var pdffilesList = new List<FileImage>();
var dirInfo = new DirectoryInfo(dir);
var files = dirInfo.GetFiles();
foreach (var file in files)
{
if (file.Extension.Contains(".pdf"))
{
pdffilesList.Add(new FileImage
{
Name = file.Name,
FullName = Regex.Match(file.FullName, "wwwroot(.*)").Groups[1].Value,
LastWriteTime = file.LastWriteTime.ToString("yyyy.MM.dd HH:mm"),
DirectoryName = file.DirectoryName,
Length = file.Length,
Extension = file.Extension
});
return Ok(pdffilesList);
}
else
{
filesList.Add(new FileImage
{
Name = file.Name,
FullName = Regex.Match(file.FullName, "wwwroot(.*)").Groups[1].Value,
LastWriteTime = file.LastWriteTime.ToString("yyyy.MM.dd HH:mm"),
DirectoryName = file.DirectoryName,
Length = file.Length,
Extension = file.Extension
});
}
}
return Ok(pdffilesList);
}
What should I change in here ?
If you just want the PDF files, then don't do anything to include the others:
foreach (var file in files)
{
if (file.Extension.Contains(".pdf"))
{
pdffilesList.Add(new FileImage
{
Name = file.Name,
FullName = Regex.Match(file.FullName, "wwwroot(.*)").Groups[1].Value,
LastWriteTime = file.LastWriteTime.ToString("yyyy.MM.dd HH:mm"),
DirectoryName = file.DirectoryName,
Length = file.Length,
Extension = file.Extension
});
// note: removed this `return`
//return Ok(pdffilesList);
}
// It's not a .pdf, so ignore it
}
return Ok(pdffilesList);
You might also consider whether you really want Contains here. Do you want to include files with extensions like ".pdfqpz" or "foopdf"? Contains will give you any file whose extension contains the string "pdf" anywhere in it. You also will miss files that have extensions ".PDF" or ".pDf", etc. You probably want something like:
if (file.Extension.Equals(".pdf", StringComparison.InvariantCultureIgnoreCase))
DirectoryInfo.GetFiles and EnumeratFiles can be used with a pattern. Instead of using separate branches you can use separate patterns:
var pattern=onlyPdfs? "*.pdf":"*";
var regex=new Regex("wwwroot(.*)");
var files=dirInfo.EnumerateFiles(pattern)
.Select(fi=>new FileImage
{
Name = file.Name,
FullName = regex.Match(file.FullName).Groups[1].Value,
LastWriteTime = file.LastWriteTime.ToString("yyyy.MM.dd HH:mm"),
DirectoryName = file.DirectoryName,
Length = file.Length,
Extension = file.Extension
});
return Ok(pdffilesList);
GetFiles waits until it finds all files and returns them in an array. EnumerateFiles on the other hand produces an IEnumerable<FileInfo> which returns each file as soon as it's found
Inside a foreach loop, i am counting and getting the full path of files with similar names, and I need to access them later so I want to make a list that saves them, and my question is how can I do this?
I´ve been trying to do it like this.
protected void ShowPng(string pathPgnImg)
{
btnNextPage.Visible = true;
string sImageName = "";
string sImagePathImages = Server.MapPath("Anexos/");
string pngFile = "";
List<string> pngs = new List<string> { pngFile };
string FileWithoutPath = Path.GetFileName(pathPgnImg);
string fileWithoutPathAndExt = Path.GetFileNameWithoutExtension(FileWithoutPath);
if(fileWithoutPathAndExt + "_pag" + LblHiddenImagePageNumber != fileWithoutPathAndExt + "_pag" + "" )
{
DirectoryInfo AnexoDirectory = new DirectoryInfo(PathForPdf);
FileInfo[] filesInDir = AnexoDirectory.GetFiles(fileWithoutPathAndExt + "_pag" + "*.png");
foreach (FileInfo foundFile in filesInDir)
{
pngFile = foundFile.FullName;
pngs = new List<string> { pngFile };
}
string sFileExt = Path.GetExtension(pngFile);
pngFile = Path.GetFileNameWithoutExtension(pngFile);
m_sImageNameUserUpload = pngFile + sFileExt;
m_sImageNameGenerated = Path.Combine(sImagePathImages, m_sImageNameUserUpload);
//Literal1.Text += "<img src=" + '"' + pngFile + '"' + "/>";
imgCrop.ImageUrl = "Anexos\\" + Path.GetFileName(pngFile);
if (m_sImageNameUserUpload != "")
{
pnlCrop.Visible = true;
imgCrop.ImageUrl = "Anexos/" + m_sImageNameUserUpload;
Session["ImageName"] = m_sImageNameUserUpload;
}
}
}
You can find what I mean in these lines here:
foreach (FileInfo foundFile in filesInDir)
{
pngFile = foundFile.FullName;
pngs = new List<string> { pngFile };
}
So what can I do? the output right now for it is although it adds the value it doesn't save it and add the other ones just adds that one to the list.
Thank you #Knoop for the answer to this simple question.
Turns out the only problem i was having was i wasn´t adding up to the list count.
So start by making a list:
List<string> Files = new List<string>;
Since i was trying to add the value of a variable that kept updating trough a foreach loop, ill use that example:
foreach (FileInfo foundFile in filesInDir)
{
pngFile = foundFile.FullName;
pngs.Add(pngFile);
}
Just to explain what i changed from the original question post to this answer was this line:
pngs.Add(pngFile);
with the name of the list and the .ADD it keeps adding the pngFile value everytime the loop restarts.
Once again thank you to #Knoop for the help.
I hope this helps some of you too.
I have code that shows the name of all .dll files within a directory on a rich textbox. How would I be able to filter/hide all filenames which I specify as unimportant and keep the rest?
Example:
Actual directory contains: 1.dll, 2.dll, 3.dll
Rich Textbox shows: 1.dll, 3.dll because 2.dll is specified as unimportant in the code.
Code I currently have that displays all files.
DirectoryInfo r = new DirectoryInfo(#"E:\SteamLibrary\steamapps\common\Grand Theft Auto V");
FileInfo[] rFiles = r.GetFiles("*.dll");
string rstr = "";
foreach (FileInfo rfile in rFiles)
{
rstr = rstr + rfile.Name + " ";
}
string strfinalR;
strfinalR = richTextBox3.Text + rstr;
richTextBox3.Text = (strfinalR);
Just make a blacklist :
string[] blacklist = new string[] { "2", "1337" };
and filter the filenames within your foreach
foreach(FileInfo rFile in rFiles)
{
if(blacklist.Any(bl => rFile.Name.Contains(bl)))
continue;
// your code
}
or when you retrieve files from r
r.GetFiles("*.dll").Where(file => !blacklist.Any( type => file.Name.Contains(type))).ToArray();
one approach is to make a list of files to ignore and then fetch all files excluding those in ignore list. Something like this:
//ignore list
List<string> filesToIgnore = new List<string>() { "2.dll", "some_other.dll" };
//get files and filter them
DirectoryInfo r = new DirectoryInfo(#"E:\SteamLibrary\steamapps\common\Grand Theft Auto V");
List<FileInfo> rFiles = r.GetFiles("*.dll").Where(x => !filesToIgnore.Contains(x.Name)).ToList();
//your existing code follows
string rstr = "";
foreach (FileInfo rfile in rFiles)
{
rstr = rstr + rfile.Name + " ";
}
string strfinalR;
strfinalR = richTextBox3.Text + rstr;
richTextBox3.Text = (strfinalR);
I can download a video from youtube but I want the sound only. How can I do that?
Code I have for downloading the video (Using VideoLibrary):
YouTube youtube = YouTube.Default;
Video vid = youtube.GetVideo(txt_youtubeurl.Text);
System.IO.File.WriteAllBytes(source + vid.FullName, vid.GetBytes());
Install the NuGet packages: MediaToolkit and VideoLibrary, it will allow you to do the conversion by file extension.
var source = #"<your destination folder>";
var youtube = YouTube.Default;
var vid = youtube.GetVideo("<video url>");
File.WriteAllBytes(source + vid.FullName, vid.GetBytes());
var inputFile = new MediaFile { Filename = source + vid.FullName };
var outputFile = new MediaFile { Filename = $"{source + vid.FullName}.mp3" };
using (var engine = new Engine())
{
engine.GetMetadata(inputFile);
engine.Convert(inputFile, outputFile);
}
The above code works awesome you don't need to download the video first I created this procedure so when rookies like myself see this makes it easier to use.
You need the nuget packages MediaToolkit and VideoLibrary.
example url: https://www.youtube.com/watch?v=lzm5llVmR2E
example path just needs a path to save file to.
just add the name of the mp3 file to save
Hope this helps someone I have tested this code;
private void SaveMP3(string SaveToFolder, string VideoURL, string MP3Name)
{
var source = #SaveToFolder;
var youtube = YouTube.Default;
var vid = youtube.GetVideo(VideoURL);
File.WriteAllBytes(source + vid.FullName, vid.GetBytes());
var inputFile = new MediaFile { Filename = source + vid.FullName };
var outputFile = new MediaFile { Filename = $"{MP3Name}.mp3" };
using (var engine = new Engine())
{
engine.GetMetadata(inputFile);
engine.Convert(inputFile, outputFile);
}
}
based on this topic, i have developed a simple and dumb program to Download a youtube playlist. Hope this helps someone. It's just a Main.cs file: Youtube Playlist Downloader - Mp4 & Mp3
Ok found a better way the above code didn't normalize the audio posting it for others.
First Add Nuget package: https://www.nuget.org/packages/NReco.VideoConverter/
To Convert MP4 to MP3
// Client
var client = new YoutubeClient();
var videoId = NormalizeVideoId(txtFileURL.Text);
var video = await client.GetVideoAsync(videoId);
var streamInfoSet = await client.GetVideoMediaStreamInfosAsync(videoId);
// Get the best muxed stream
var streamInfo = streamInfoSet.Muxed.WithHighestVideoQuality();
// Compose file name, based on metadata
var fileExtension = streamInfo.Container.GetFileExtension();
var fileName = $"{video.Title}.{fileExtension}";
// Replace illegal characters in file name
fileName = RemoveIllegalFileNameChars(fileName);
tmrVideo.Enabled = true;
// Download video
txtMessages.Text = "Downloading Video please wait ... ";
//using (var progress = new ProgressBar())
await client.DownloadMediaStreamAsync(streamInfo, fileName);
// Add Nuget package: https://www.nuget.org/packages/NReco.VideoConverter/ To Convert MP4 to MP3
if (ckbAudioOnly.Checked)
{
var Convert = new NReco.VideoConverter.FFMpegConverter();
String SaveMP3File = MP3FolderPath + fileName.Replace(".mp4", ".mp3");
Convert.ConvertMedia(fileName, SaveMP3File, "mp3");
//Delete the MP4 file after conversion
File.Delete(fileName);
LoadMP3Files();
txtMessages.Text = "File Converted to MP3";
tmrVideo.Enabled = false;
txtMessages.BackColor = Color.White;
if (ckbAutoPlay.Checked) { PlayFile(SaveMP3File); }
return;
}
I like the idea of using a method. I tried SaveMP3() but it had some problems.
This worked for me: `
private void SaveMP3(string SaveToFolder, string VideoURL, string MP3Name)
{
string source = SaveToFolder;
var youtube = YouTube.Default;
var vid = youtube.GetVideo(VideoURL);
string videopath = Path.Combine(source, vid.FullName);
File.WriteAllBytes(videopath, vid.GetBytes());
var inputFile = new MediaFile { Filename = Path.Combine(source, vid.FullName) };
var outputFile = new MediaFile { Filename = Path.Combine(source , $"{MP3Name}.mp3") };
using (var engine = new Engine())
{
engine.GetMetadata(inputFile);
engine.Convert(inputFile, outputFile);
}
File.Delete(Path.Combine(source, vid.FullName));
}
`
I need to get the path of the currently selected File or Folder in Windows Explorer to put the ListView. I do not know how to do hope you can help.Thank you
Update Source
public void GetListFileAndFolderOfWindowsExploer()
{
try
{
string fileName;
ArrayList selected = new ArrayList();
Shell32.Shell shell = new Shell32.Shell();
foreach (SHDocVw.InternetExplorer windows in new SHDocVw.ShellWindows())
{
fileName = Path.GetFileNameWithoutExtension(windows.FullName).ToLower();
if (fileName.ToLowerInvariant() == "explorer")
{
Shell32.FolderItems items = ((Shell32.IShellFolderViewDual2)windows.Document).SelectedItems();
foreach (Shell32.FolderItem item in items)
{
lift = new string[] { item.Name, item.Path };
ListViewItem list = new ListViewItem();
list.Text = item.Name;
list.SubItems.Add(item.Path);
list.UseItemStyleForSubItems = true;
listView1.Items.Add(list);
}
}
}
}
catch (Exception ex)
{
writelog(ex.Message);
}
}
You can use an OpenFileDialog(Home and learn OpenFileDialog).
Hope this link helps.
OpenFileDialog fdlg = new OpenFileDialog();
fdlg.Title = "C# Help";
fdlg.InitialDirectory = #"c:\";
fdlg.Filter = "All files (*.*)|*.*|All files (*.*)|*.*";
fdlg.FilterIndex = 2;
fdlg.RestoreDirectory = true;
if (fdlg.ShowDialog() == DialogResult.OK)
{
string dirName =
System.IO.Path.GetDirectoryName(fdlg.FileName);
string drive =
dirName.Split(System.IO.Path.VolumeSeparatorChar)[0];
MessageBox.Show(dirName);
MessageBox.Show(drive);
}
To in order to get selected items you have to use the following interfaces:
IServiceProvider
IShellBrowser
IFolderView
IShellFolder2
IPersistFolder2
or directly
(IEnumIDList and LPITEMIDLIST) foreach all selected items
This works fine in Windows 10.
Your question seems unclear,Hope you are using OpenFileDialog for selecting files,
If you're looking for the file path:
string path = OpenFileDialog1.FileName; //output = c:\folder\file.txt
If you're looking for the directory path:
string path = Path.GetDirectoryName(OpenFileDialog1.FileName); //output = c:\folder
In general, the System.IO.Path class has a lot of useful features for retrieving and manipulating path information.