I'm trying to add images from a folder and their names below each image. In master slide[0] there should be Title. My problem is that my code is generating single PowerPoint file for each image instead of adding all images to one PowerPoint file. Can someone help me with my come or simar code that can work out
I've attached an image of what I'm trying to achieve.
Here's the code I'm working with using C# and GemBoxPresentation API:
//Create new powerpoint presentation
var presentation = new PresentationDocument();
//change the path format
string dir = txtPath.Text.Replace("/", "\\");
fontRootFolder = dir.Replace(Path.GetDirectoryName(dir) + Path.DirectorySeparatorChar, "");
string workingPath = Application.StartupPath + #"\Zip Extracts\" + fontRootFolder + "\\png";
if (Directory.Exists(workingPath))
{
// Get the directory
DirectoryInfo ImagePath = new DirectoryInfo(workingPath);
// Using GetFiles() method to get list of all png files present in the png folder
FileInfo[] Files = ImagePath.GetFiles();
foreach (FileInfo fi in Files)
{
for (int i = 0; i < fi.Length; i++)
{
Cursor = Cursors.WaitCursor;
// Get slide size.
var size = presentation.SlideSize;
// Set slide size.
size.SizedFor = SlideSizeType.OnscreenShow16X10;
size.Orientation = GemBox.Presentation.Orientation.Landscape;
size.NumberSlidesFrom = 1;
// Create new presentation slide.
var slide = presentation.Slides.AddNew(SlideLayoutType.Custom);
// Create first picture from path.
Picture picture = null;
using (var stream = File.OpenRead(fi.FullName))
picture = slide.Content.AddPicture(PictureContentType.Png, stream, 1.45, 1.35, 1.45, 1.35, LengthUnit.Centimeter);
var textBox = slide.Content.AddTextBox(ShapeGeometryType.Rectangle, 1.03, 1.03, 6, 6, LengthUnit.Centimeter);
var paragraph = textBox.AddParagraph();
paragraph.Format.Alignment = GemBox.Presentation.HorizontalAlignment.Center;
paragraph.AddRun(fi.Name);
SaveFileDialog sfd = new SaveFileDialog();
sfd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
sfd.Title = "Save PowerPoint Icons";
sfd.CheckFileExists = false;
sfd.CheckPathExists = true;
sfd.DefaultExt = "pptx";
sfd.Filter = "Powerpoint Files (*.pptx) | *.pptx";
sfd.FilterIndex = 1;
sfd.RestoreDirectory = true;
if (sfd.ShowDialog() == DialogResult.OK)
{
//string file = sfd.FileName;
presentation.Save(sfd.FileName);
Cursor = Cursors.Default;
}
Cursor = Cursors.Default;
}
}
}
Expected PowerPoint output
I developed a similar tool.
The base class:
using System;
using System.Collections.Generic;
namespace akGraphics2Pptx
{
class GraphicsConverter
{
static string[] usageText =
{
"akGraphics2Pptx - Graphics to Powerpoint/PDF Converter",
"------------------------------------------------------",
"",
"Usage:",
"",
"akGraphics2Pptx graphics_file [graphics_file ...] output_file",
"",
"Enter more than one graphics file name to get more than one slide.",
"Type of output file can be .pptx or .pdf",
""
};
protected IEnumerable<string> getFileNames(string[] args, string[] extensions)
{
List<string> names = new List<string>();
foreach (string arg in args)
{
foreach (string ext in extensions)
{
if (arg.ToLower().EndsWith("." + ext))
{
names.Add(arg);
break;
}
}
}
return names;
}
/// <summary>
/// Create a Powerpoint file with one slide per graphics file argument.
/// The arguments can have any order. The files are distinguished by their extensions.
/// </summary>
/// <param name="args">The arguments</param>
public virtual void convert(string[] args)
{
}
protected void usage()
{
foreach (string s in usageText)
{
Console.WriteLine(s);
}
}
}
}
The specific converter for PowerPoint output (I also have a PDF output):
using System;
using System.Collections.Generic;
using System.Linq;
using Ppt = Microsoft.Office.Interop.PowerPoint;
using static Microsoft.Office.Core.MsoTriState;
using System.IO;
namespace akGraphics2Pptx
{
class Graphics2PptxConverter : GraphicsConverter
{
private static string[] knownGraphicsFileExtensions = { "gif", "jpg", "png", "tif", "bmp", "wmf", "emf" };
private static string[] powerpointFileExtensions = { "ppt", "pptx" };
private IEnumerable<string> getGraphicsFileNames(string[] args)
{
return getFileNames(args, knownGraphicsFileExtensions);
}
private IEnumerable<string> getPowerpointFileNames(string[] args)
{
return getFileNames(args, powerpointFileExtensions);
}
/// <summary>
/// Create a Powerpoint file with one slide per graphics file argument.
/// The arguments can have any order. The files are distinguished by their extensions.
/// </summary>
/// <param name="args">The arguments</param>
public void convert(string[] args)
{
var graphicsFileNames = getGraphicsFileNames(args);
var powerpointFileNames = getPowerpointFileNames(args);
if (!graphicsFileNames.Any() || (powerpointFileNames.Count() != 1))
{
usage();
}
else
{
// inspired by http://stackoverflow.com/a/26372266/1911064
Ppt.Application pptApplication = new Ppt.Application();
// Create the Presentation File
Ppt.Presentation pptPresentation =
pptApplication.Presentations.Add(WithWindow: msoFalse);
Ppt.CustomLayout customLayout =
pptPresentation.SlideMaster.CustomLayouts[Ppt.PpSlideLayout.ppLayoutText];
foreach (string graphicsFileName in graphicsFileNames)
{
if (!File.Exists(graphicsFileName))
{
Console.WriteLine($"Graphics file {graphicsFileName} not found!");
}
else
{
// Create new Slide
Ppt.Slides slides = pptPresentation.Slides;
Ppt._Slide slide =
slides.AddSlide(Index: slides.Count + 1, pCustomLayout: customLayout);
// Add title
Ppt.TextRange objText = slide.Shapes[1].TextFrame.TextRange;
objText.Text = Path.GetFileName(graphicsFileName);
objText.Font.Name = "Arial";
objText.Font.Size = 32;
Ppt.Shape shape = slide.Shapes[2];
objText = shape.TextFrame.TextRange;
objText.Text = "Content goes here\nYou can add text";
string fullName = Path.GetFullPath(graphicsFileName);
slide.Shapes.AddPicture(fullName, msoFalse, msoTrue, shape.Left, shape.Top, shape.Width, shape.Height);
slide.NotesPage.Shapes[2].TextFrame.TextRange.Text = graphicsFileName;
}
}
string pptFullName = Path.GetFullPath(powerpointFileNames.First());
Console.WriteLine("Powerpoint file created: " + pptFullName);
Console.WriteLine("Graphics slides: " + pptPresentation.Slides.Count);
Console.WriteLine("");
pptPresentation.SaveAs(pptFullName, Ppt.PpSaveAsFileType.ppSaveAsDefault, msoTrue);
pptPresentation.Close();
pptApplication.Quit();
}
}
}
}
Aspose.Slides for .NET is a Presentation Processing API for PowerPoint and OpenOffice formats. Aspose.Slides enable applications to read, write, protect, modify and convert presentations in .NET C#. Manage presentation text, shapes, charts, tables & animations, add audio & video to slides and preview slides.
More Link: https://products.aspose.com/slides/net/
internal class Program
{
static void Main(string[] args)
{
string[] filesindirectory = Directory.GetFiles(#"C:\\IMG");// file folder
string NameOfPPT = "_PPT_" + DateTime.Now.ToString("yyyy-MM-dd HH.mm.ss");
//////////// var workbook = new Workbook(img);
//////////// workbook.Save(img);
using (Presentation pres = new Presentation())
{
int SlideIndex = 0;
foreach (string img in filesindirectory)
{
int alpha = 200, red = 200, green = 200, blue = 200;
pres.Slides.AddEmptySlide(pres.LayoutSlides[SlideIndex]);
// Get the first slide
ISlide slide = pres.Slides[SlideIndex];
//Add an AutoShape of Rectangle type
IAutoShape ashp = slide.Shapes.AddAutoShape(ShapeType.Rectangle, 5, 5, 700, 30);
//Add ITextFrame to the Rectangle
string Header = "Store: Name of Store |"+ SlideIndex.ToString() + " Visite Date: 2022-Sep-20 |" + "Category: ABC" + SlideIndex.ToString();
ashp.AddTextFrame(Header);
//Change the text color to Black (which is White by default)
ashp.TextFrame.Paragraphs[0].Portions[0].PortionFormat.FillFormat.FillType = FillType.Solid;
ashp.TextFrame.Paragraphs[0].Portions[0].PortionFormat.FillFormat.SolidFillColor.Color = Color.Black;
//Change the line color of the rectangle to White
ashp.ShapeStyle.LineColor.Color = System.Drawing.Color.DarkGoldenrod;
pres.HeaderFooterManager.SetAllHeadersText("Adding Header");
pres.HeaderFooterManager.SetAllHeadersVisibility(true);
pres.HeaderFooterManager.SetAllFootersText("System Auto generated");
pres.HeaderFooterManager.SetAllFootersVisibility(true);
// pres.HeaderFooterManager.SetAllDateTimesText(DateTime.Now.ToString("dd/MM/yyyy"));
// pres.HeaderFooterManager.SetAllDateTimesVisibility(true);
SlideIndex++;
// Instantiate the ImageEx class
System.Drawing.Image imgs = (System.Drawing.Image)new Bitmap(img);
IPPImage imgx = pres.Images.AddImage(imgs);
// Add Picture Frame with height and width equivalent of Picture
//IPictureFrame pf = slide.Shapes.AddPictureFrame(ShapeType.Rectangle, 5, 5, 707, 525, imgx);// full placed image
IPictureFrame pf = slide.Shapes.AddPictureFrame(ShapeType.Rectangle, 60,100, 600, 400, imgx);
// Apply some formatting to PictureFrameEx
pf.LineFormat.FillFormat.FillType = FillType.Gradient;
pf.LineFormat.FillFormat.SolidFillColor.Color = Color.Black;
pf.LineFormat.Width = 5;
pf.Rotation = 0;
// Get the center of the slide and calculate watermark's position
PointF center = new PointF(pres.SlideSize.Size.Width / 2, pres.SlideSize.Size.Height / 2);
float width = 100;
float height = 50;
float x = center.X - width / 2;
float y = center.Y - height / 2;
// Add watermark shape
IAutoShape watermarkShape = slide.Shapes.AddAutoShape(ShapeType.Rectangle, x, y, width, height);
// Set fill type
watermarkShape.FillFormat.FillType = FillType.NoFill;
watermarkShape.LineFormat.FillFormat.FillType = FillType.NoFill;
// Set rotation angle
watermarkShape.Rotation = -45;
// Set text
ITextFrame watermarkTextFrame = watermarkShape.AddTextFrame("OOOOOOPPPPP");
IPortion watermarkPortion = watermarkTextFrame.Paragraphs[0].Portions[0];
// Set font size and fill type of the watermark
watermarkPortion.PortionFormat.FontHeight = 20;
watermarkPortion.PortionFormat.FillFormat.FillType = FillType.Solid;
watermarkPortion.PortionFormat.FillFormat.SolidFillColor.Color = System.Drawing.Color.FromArgb(alpha, red, green, blue);
// Lock Shapes from modifying
watermarkShape.ShapeLock.SelectLocked = false;
watermarkShape.ShapeLock.SizeLocked = false;
watermarkShape.ShapeLock.TextLocked = false;
watermarkShape.ShapeLock.PositionLocked = false;
watermarkShape.ShapeLock.GroupingLocked = false;
}
pres.Save(#"C:\\IMG\\PPT\\" + NameOfPPT + ".pptx", Aspose.Slides.Export.SaveFormat.Pptx);
}
}
}
Using free plugin
public bool createPPT()
{
var data = DbWORKINGDbContext.AMR_IMG_TO_PPT_POC.Where(c => c.PPTSlideInserted == false && c.Downloaded == true).ToList();
// var data = DbWORKINGDbContext.AMR_IMG_TO_PPT_POC.Take(10).ToList();
if (data.Count > 0)
{
Application pptApplication = new Application();
Microsoft.Office.Interop.PowerPoint.Slides slides;
Microsoft.Office.Interop.PowerPoint._Slide slide;
Microsoft.Office.Interop.PowerPoint.TextRange objText;
// Microsoft.Office.Interop.PowerPoint.TextRange objText2;
// Create the Presentation File
Presentation pptPresentation = pptApplication.Presentations.Add(MsoTriState.msoTrue);
Microsoft.Office.Interop.PowerPoint.CustomLayout customLayout = pptPresentation.SlideMaster.CustomLayouts[Microsoft.Office.Interop.PowerPoint.PpSlideLayout.ppLayoutText];
int SlideIndex = 1;
foreach (AMR_IMG_TO_PPT_POC POCdata in data)
{
var pictureFileName = ImageToPptApp.Util.Constant.ImageStorePath + POCdata.Id + ".jpg";
var StoreName = POCdata.StoreName;
var Url = POCdata.FileCloudUrl;
var Filename = POCdata.Id;
var Titile = POCdata.Title;
var PictureTime = POCdata.PictureTimeStamp;
string Header = "Store: " + StoreName.ToString() + " | Date Time:" + PictureTime.ToString() + " | Titile: " + Titile.ToString();
// Create new Slide
slides = pptPresentation.Slides;
slide = slides.AddSlide(SlideIndex, customLayout);
// Add title
objText = slide.Shapes[1].TextFrame.TextRange;
objText.Text = Header;
objText.Font.Name = "Arial";
objText.Font.Size = 20;
//objText2 = slide.Shapes[2].TextFrame.TextRange;
//objText2.Text = "test";
//objText2.Font.Name = "Arial";
//objText2.Font.Size = 10;
//objText = slide.Shapes[2].TextFrame.TextRange;
//objText.Text = "pp";
Microsoft.Office.Interop.PowerPoint.Shape shape = slide.Shapes[2];
slide.Shapes.AddPicture(pictureFileName, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoTrue, 100, 100, 600, 400);
slide.NotesPage.Shapes[2].TextFrame.TextRange.Text = "MintPlus";
SlideIndex++;
}
pptPresentation.SaveAs(ImageToPptApp.Util.Constant.PptStorePath + "ppp"+ ".pptx", Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsDefault, MsoTriState.msoTrue);
pptPresentation.Close();
pptApplication.Quit();
}
return true;
}
I am using the following code to create a file at a temp path and then delete it after the print happened successfully. But after printing I try to dispose the file and when I try to delete the file, I still get an exception saying "The process cannot access the file 'Chart0.png' because it is being used by another process." Please help.
I also tried putting the deleting code in the finally block but still no luck.
public static bool PrintAllCharts(Dictionary<string, ILightningChartInterface> charts)
{
DirectoryInfo info = null;
try
{
string FilePathWithoutFileName = string.Empty;
info = Directory.CreateDirectory(#"C:\TempCharts");
for (int i = 0; i < charts.Count; i++)
{
KeyValuePair<string, ILightningChartInterface> kp = charts.ElementAt(i);
FilePathWithoutFileName = info.FullName;
string FullPath = string.Format("{0}/Chart{1}.png", FilePathWithoutFileName, i.ToString());
kp.Value.SaveChartToFile(FullPath);
}
var files = Directory.GetFiles(FilePathWithoutFileName);
using (var pdoc = new PrintDocument())
{
using (var pdi = new System.Windows.Forms.PrintDialog { Document = pdoc, UseEXDialog = true })
{
if (pdi.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
pdoc.PrinterSettings = pdi.PrinterSettings;
pdoc.PrintPage += Pdoc_PrintPage;
foreach (var file in files)
{
pdoc.DocumentName = file;
pdoc.Print();
}
}
}
}
//Dispose the file after printing.
foreach(var file in files)
{
Image.FromFile(file).Dispose();
File.Delete(file); //This line gives an exception
}
foreach (DirectoryInfo dir in info.GetDirectories())
{
dir.Delete(true);
}
return true;
}
catch (Exception ex)
{
return false;
}
}
private static void Pdoc_PrintPage(object sender, PrintPageEventArgs e)
{
string file = ((PrintDocument)sender).DocumentName;
System.Drawing.Image img = System.Drawing.Image.FromFile(file);
Rectangle m = e.MarginBounds;
if ((double)img.Width / (double)img.Height > (double)m.Width / (double)m.Height) // image is wider
{
m.Height = (int)((double)img.Height / (double)img.Width * (double)m.Width);
}
else
{
m.Width = (int)((double)img.Width / (double)img.Height * (double)m.Height);
}
e.Graphics.DrawImage(img, m);
}
The issue lies in your Pdoc_PrintPage method. You're using the following line to read the file:
System.Drawing.Image img = System.Drawing.Image.FromFile(file);
The docs for FromFile state:
The file remains locked until the Image is disposed.
So really you should write your code like this, so that the image is disposed of (and the file unlocked) after you're done with it:
string file = ((PrintDocument)sender).DocumentName;
using (System.Drawing.Image img = System.Drawing.Image.FromFile(file))
{
Rectangle m = e.MarginBounds;
if ((double)img.Width / (double)img.Height > (double)m.Width / (double)m.Height) // image is wider
{
m.Height = (int)((double)img.Height / (double)img.Width * (double)m.Width);
}
else
{
m.Width = (int)((double)img.Width / (double)img.Height * (double)m.Height);
}
e.Graphics.DrawImage(img, m);
}
Note that you have to dispose of the same image instance. You currently have this code in your delete loop:
Image.FromFile(file).Dispose();
That's simply trying to load a second copy of the file and then immediately dispose of it. Once you have implemented the above change, you should also remove this line from your delete loop.
I am trying to open a print preview dialog and Print all the images. My problem is when I am printing the image, the width doesn't seem to be aligning with printer paper and the image is getting cut. How can I print the image on the paper without cutting it. Please help.
Please see Pdoc_PrintPage event method. I am using e.Graphics.DrawImageUnscaled is it the right overload that I am using. I debug my code put in the values.
private void PrintAllCharts(Dictionary<LightningChartUserControl, string> charts)
{
try
{
if (PrinterSettings.InstalledPrinters.Count == 0)
{
Xceed.Wpf.Toolkit.MessageBox.Show(System.Windows.Application.Current.TryFindResource("SetUpPrinter").ToString(),
"Default printer not found", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
string FilePathWithoutFileName = string.Empty;
DirectoryInfo info = Directory.CreateDirectory(#"C:\TempCharts");
for (int i = 0; i < charts.Count; i++)
{
KeyValuePair<LightningChartUserControl, string> kp = charts.ElementAt(i);
FilePathWithoutFileName = info.FullName;
string FullPath = string.Format("{0}/Chart{1}.png", FilePathWithoutFileName, i.ToString());
kp.Key.Chart.SaveToFile(FullPath);
}
var files = Directory.GetFiles(FilePathWithoutFileName);
using(var pdoc=new PrintDocument())
{
using(var pdi=new System.Windows.Forms.PrintDialog { Document = pdoc, UseEXDialog = true })
{
if (pdi.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
pdoc.PrinterSettings = pdi.PrinterSettings;
pdoc.PrintPage += Pdoc_PrintPage;
foreach(var file in files)
{
pdoc.DocumentName = file;
pdoc.Print();
}
}
}
}
PrinterSettings settings = new PrinterSettings();
Xceed.Wpf.Toolkit.MessageBox.Show(string.Format(System.Windows.Application.Current.TryFindResource("PrintSuccessful").ToString(),settings.PrinterName),
"Print Successful", MessageBoxButton.OK);
foreach(FileInfo file in info.GetFiles())
{
file.Delete();
}
foreach (DirectoryInfo dir in info.GetDirectories())
{
dir.Delete(true);
}
}
catch (Exception ex)
{
SystemDebugLogLogger.LogError(ex);
}
}
private void Pdoc_PrintPage(object sender, PrintPageEventArgs e)
{
string file = ((PrintDocument)sender).DocumentName;
System.Drawing.Image img = System.Drawing.Image.FromFile(file);
//e.Graphics.DrawImage(img, e.MarginBounds);
//e.Graphics.DrawImageUnscaled(img, e.MarginBounds);
var hei = img.Height; //509
var wid = img.Width; //1671
int x1 = e.MarginBounds.Left;//100
int y1 = e.MarginBounds.Top;//100
int w = e.MarginBounds.Width;//650
int h = e.MarginBounds.Height;//900
e.Graphics.DrawImageUnscaled(img, x1, y1, w, h);
}
I am making a simple app which will show the images from a specific folder on a winform load.
I've done the "showing part" with using openfileDialog and it's working fine, where the user has to select images each time.I want to make it more automatic that user doesn't have to select the files, It should select the files automatically.
Target Folder is static(It'll remain same) while it contains multiple images.
How can I obtain all of the image files from the directory?
I am using this code.
string[] path = Directory.GetFiles("Cards");
foreach (string filepath in path)
{
string[] files = filepath;
int x = 20;
int y = 20;
int maxheight = -1;
foreach (string img in files)
{
PictureBox pic = new PictureBox();
pic.Image = Image.FromFile(img);
pic.Location = new Point(x, y);
pic.Size = new Size(200, 200);
pic.SizeMode = PictureBoxSizeMode.Zoom;
x += pic.Width + 10;
maxheight = Math.Max(pic.Height, maxheight);
if (x > this.ClientSize.Width - 100)
{
x = 20;
y += maxheight + 10;
}
this.panelImages.Controls.Add(pic);
}
}
but stuck at string[] files = filepath; here.
Please guide me where I am making any mistake.
Please let me know if anybody needs more info.
Thanks in advance.
Consider changing:
string[] path = Directory.GetFiles("Cards");
foreach (string filepath in path)
{
string[] files = filepath;
to:
string[] files = Directory.GetFiles("Cards");
Then your later:
foreach (string img in files)
will iterate over all file in the Cards folder.
There are some dangers in passing in just "Cards" as a parameter, as per the docs:
Relative path information is interpreted as relative to the current
working directory.
It would be better, if possible, to pass an absolute path.
I started to experiment with the new Unity beta 5.6 Video Player. I have made a media player to loop images and videos from a folder (url) on a RawImage.
When I add larger video files (trailers) to the folder, at some point pretty soon the Player gets stuck after the video has ended and does not leave the while (videoPlayer.isPlaying) loop. At same time the rendering stops completely from the profiler tool. This does not happen with smaller & shorter video clips.
Also there is a small bug with audio. The audio wont play on first loop with first video file. After that it plays fine.
Have I made some mistake or could this be a bug in the beta? I have only tested with .mp4 videos.
Edit: Seems like a workaround fix for now is to add videoPlayer.isLooping = true; after videoPlayer.Play(); command. Code updated.
Code so far ->
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Net;
using System.Text.RegularExpressions;
using UnityEngine.Video;
public class Play : MonoBehaviour
{
// Use this for initialization
bool develop = true;
bool web = false;
//UI & Audio
private VideoPlayer videoPlayer;
private VideoSource videoSource;
private AudioSource audioSource;
//Local
private string path = "file://";
private string folder = "C:/medias/";
private WaitForSeconds waitTime;
int arrLength;
int i = 0;
//Web (http)
private string webpath = "http://";
string uri = "www.rtcmagazine.com/files/images/5353/";
string source;
string str;
WWW www;
//Extensions to get
string[] extensions = new[] { ".jpg", ".JPG", ".jpeg", ".JPEG", ".png", ".PNG", ".mp4", ".MP4", ".webm", ".WEBM", ".avi", ".AVI" };
FileInfo[] info;
DirectoryInfo dir;
void Start()
{
//Add VideoPlayer to the GameObject
videoPlayer = gameObject.AddComponent<VideoPlayer>();
//Add AudioSource
audioSource = gameObject.AddComponent<AudioSource>();
//Disable Play on Awake for both Video and Audio
videoPlayer.playOnAwake = true;
audioSource.playOnAwake = true;
if (web) {
string[] fetchFilesCount = GetFiles (webpath+uri);
int getLenght = fetchFilesCount.Length;
info = new FileInfo[getLenght];
int counter = 0;
string[] filesFromWeb = GetFiles (webpath+uri);
foreach (String file in filesFromWeb)
{
info [counter] = new FileInfo(webpath+uri+file);
counter++;
if (counter == filesFromWeb.Length) {
counter = 0;
}
}
} else {
info = new FileInfo[]{};
dir = new DirectoryInfo(#folder);
info = dir.GetFiles().Where(f => extensions.Contains(f.Extension.ToLower())).ToArray();
}
arrLength = info.Length;
Application.runInBackground = true;
StartCoroutine(looper());
}
IEnumerator looper()
{
//Run forever
while (true)
{
if (i == arrLength - 1)
{
if (web) {
int counter = 0;
string[] filesFromWeb = GetFiles (webpath+uri);
foreach (String file in filesFromWeb)
{
info [counter] = new FileInfo(webpath+uri+file);
counter++;
if (counter == filesFromWeb.Length) {
counter = 0;
}
}
} else {
info = dir.GetFiles ().Where (f => extensions.Contains (f.Extension.ToLower ())).ToArray ();
arrLength = info.Length;
}
i = 0;
}
else
{
i++;
}
//Debug.Log(info[i]);
yield return StartCoroutine(medialogic());
int dotIndex = info[i].ToString().LastIndexOf('.');
//string lhs = index < 0 ? source : source.Substring(0,index),
string searchDot = dotIndex < 0 ? "" : source.Substring(dotIndex+1);
int dotPos = Array.IndexOf(extensions, "." + searchDot);
if (dotPos > 5) {
waitTime = new WaitForSeconds (0);
} else {
waitTime = new WaitForSeconds (7);
}
//Wait for 7 seconds
yield return waitTime;
}
}
IEnumerator medialogic()
{
source = info[i].ToString();
if (web) {
if (develop) {
www = new WWW (source);
} else {
www = new WWW (webpath+uri+source);
}
} else {
if (develop) {
str = path + source;
} else {
str = path + folder + source;
}
www = new WWW (str);
}
int index = source.LastIndexOf('.');
//string lhs = index < 0 ? source : source.Substring(0,index),
string rhs = index < 0 ? "" : source.Substring(index+1);
int pos = Array.IndexOf(extensions, "." + rhs);
if (pos > -1 && pos < 6)
{
//Wait for download to finish
yield return www;
GetComponent<RawImage>().texture = www.texture;
}
else if (pos > 5)
{
//videos here
videoPlayer.source = VideoSource.Url;
videoPlayer.url = str;
//Set Audio Output to AudioSource
videoPlayer.audioOutputMode = VideoAudioOutputMode.AudioSource;
//Assign the Audio from Video to AudioSource to be played
videoPlayer.EnableAudioTrack(0, true);
videoPlayer.SetTargetAudioSource(0, audioSource);
//Set video To Play then prepare Audio to prevent Buffering
videoPlayer.Prepare();
while (!videoPlayer.isPrepared)
{
yield return null;
}
//Assign the Texture from Video to RawImage to be displayed
GetComponent<RawImage>().texture = videoPlayer.texture;
//Play Video
videoPlayer.Play();
//Play Sound
audioSource.Play();
//Set loop to true, hack for a freeze bug
videoPlayer.isLooping = true;
//Alternative way to check if video has ended
videoPlayer.loopPointReached += EndReached;
Debug.Log ("Play started");
while (videoPlayer.isPlaying)
{
Debug.Log ("---Playing---");
yield return null;
}
Debug.Log("Done Playing Video");
}
}
void EndReached(UnityEngine.Video.VideoPlayer videoPlayer) {
Debug.Log("End reached!");
//Play Video
videoPlayer.Stop();
//Play Sound
audioSource.Stop();
}
public static string[] GetFiles(string url)
{
string[] extensions2 = new[] { ".jpg", ".JPG", ".jpeg", ".JPEG", ".png", ".PNG", ".mp4", ".MP4", ".webm", ".WEBM", ".avi", ".AVI" };
List<string> files = new List<string>(500);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
string html = reader.ReadToEnd();
Regex regex = new Regex("(?<name>.*)");
MatchCollection matches = regex.Matches(html);
if (matches.Count > 0)
{
foreach (Match match in matches)
{
if (match.Success)
{
string[] matchData = match.Groups[0].ToString().Split('\"');
foreach (string x in extensions2)
{
if (match.ToString().Contains(x))
{
files.Add(matchData[1]);
}
}
//files.Add(matchData[1]);
}
}
}
}
}
return files.ToArray();
}
public static string[] getFtpFolderItems(string ftpURL)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpURL);
request.Method = WebRequestMethods.Ftp.ListDirectory;
//You could add Credentials, if needed
//request.Credentials = new NetworkCredential("anonymous", "password");
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
return reader.ReadToEnd().Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
}
}
Thanks for your time :)