Beispiel #1
0
        public void TestGetExtension()
        {
            var tempLongPathFilename = Path.Combine(longPathDirectory, Path.GetRandomFileName());

            Assert.AreEqual(tempLongPathFilename.Substring(tempLongPathFilename.Length - 4, 4),
                            Path.GetExtension(tempLongPathFilename));
        }
        public static void RenameFileExtension(string iPath, string src, string dest)
        {
            if (!Directory.Exists(iPath))
            {
                return;
            }

            // rename subDir
            string[] dirPaths = Directory.GetDirectories(iPath);
            for (int i = 0; i < dirPaths.Length; i++)
            {
                RenameFileExtension(dirPaths[i], src, dest);
            }

            // rename files
            string[] filePaths = Directory.GetFiles(iPath);
            for (int i = 0; i < filePaths.Length; ++i)
            {
                string extension = Path.GetExtension(filePaths[i]);
                if (extension == src)
                {
                    string dir      = Path.GetDirectoryName(filePaths[i]);
                    string name     = Path.GetFileNameWithoutExtension(filePaths[i]);
                    string destFile = dir + name + dest;

                    MoveWithReplace(filePaths[i], destFile);
                }
            }
        }
 /// <summary>
 /// Init database connection.
 /// </summary>
 /// <param name="dbPath">Database file path</param>
 /// <returns>Boolean value determine the database is open successful or not</returns>
 public bool InitDb(string dbPath)
 {
     if (File.Exists(dbPath))
     {
         if (Path.GetExtension(dbPath).Equals(".db"))
         {
             DatabaseConnection = new SQLiteConnection($"Data Source={dbPath}; Version=3;FailIfMissing=True");
             DatabaseConnection.Open();
             bgwGetCourse.ReportProgress(1, new Log()
             {
                 Text = "Database connection opened.", TextColor = Color.Green, NewLine = true
             });
             return(true);
         }
         bgwGetCourse.ReportProgress(1, new Log()
         {
             Text = "File is not a database file.", TextColor = Color.Red
         });
         return(false);
     }
     bgwGetCourse.ReportProgress(1, new Log()
     {
         Text = "Invalid file path.", TextColor = Color.Red
     });
     return(false);
 }
Beispiel #4
0
        public static bool IsValidFile(string path)
        {
            string extension = Path.GetExtension(path).ToUpper();

            if (_OutlookExtensions.Contains(extension))
            {
                return(true);
            }
            return(false);
        }
Beispiel #5
0
 public IResult <string> GetFileExtension(string fileName)
 {
     try
     {
         return(new SuccessResult <string>(Path.GetExtension(fileName)));
     }
     catch (Exception e)
     {
         return(new FailureResult <string>(e));
     }
 }
Beispiel #6
0
        public static bool IsVideo(string fileName)
        {
            List <string> videoExtensions = GetVideoExtensions();

            if (videoExtensions.Count == 0)
            {
                return(false);
            }

            if (videoExtensions.Contains(Path.GetExtension(fileName).Replace(".", "").Trim().ToUpper()))
            {
                return(true);
            }

            return(false);
        }
Beispiel #7
0
        static void ProcessFolder(string rootPath, string baseFolder, string destFolder, bool canMove, bool preservePaths, string extraPath = "")
        {
            var folder = baseFolder;
            var files  = Directory.EnumerateFiles(folder, "*").Where(f => Path.GetExtension(f) != ".txt" && Path.GetExtension(f) != ".nfo" && Path.GetExtension(f) != ".sfv").ToArray();

            while (!preservePaths)              // Not a true while, preserve paths does not change.
            {
                var subFolders = Directory.EnumerateDirectories(folder).ToArray();
                if (files.Length == 0 && subFolders.Length == 1)
                {
                    folder = subFolders[0];
                }
                else
                {
                    break;
                }
                files = Directory.EnumerateFiles(folder, "*").Where(f => Path.GetExtension(f) != ".txt" && Path.GetExtension(f) != ".nfo" && Path.GetExtension(f) != ".sfv").ToArray();
            }

            //files = Directory.EnumerateFiles(folder, "*", SearchOption.AllDirectories).ToArray();
            var archiveFiles = GetArchiveFiles(files);

            archiveFiles.ForEach(archive => ProcessArchive(rootPath, Path.GetDirectoryName(archive), archive, files, destFolder));

            var names = folder.Substring(rootPath.Length).Split(Path.DirectorySeparatorChar);
            var name  = names.FirstOrDefault(n => Regex.IsMatch(n, "KONTAKT", RegexOptions.IgnoreCase)) ?? names[0];

            //if ((folder + "\\").StartsWith(string.Format("{0}\\{1}\\", baseFolder, name)))
            //	name = "";
            //name = Regex.Replace(name, @"\.(rar|r00|zip|iso)$", "", RegexOptions.IgnoreCase);
            name = Regex.Replace(name, @"\.(rar|r00|zip)$", "", RegexOptions.IgnoreCase);
            name = Regex.Replace(name, @"\.part1", "", RegexOptions.IgnoreCase);
            name = Regex.Replace(name, @"\.part01", "", RegexOptions.IgnoreCase);
            name = Regex.Replace(name, "-", " ");
            name = Regex.Replace(name, @"([a-z ])\.+([\w ])", "$1 $2", RegexOptions.IgnoreCase);                // Remove dots but leave those that are between digits.
            name = Regex.Replace(name, @"([\w ])\.+([a-z ])", "$1 $2", RegexOptions.IgnoreCase);
            name = Regex.Replace(name, @"\b(HYBRID|DYNAMiCS|PROPER|VSTi|RTAS|CHAOS|AMPLiFY|AU|MATRiX|DVDR|WAV|AiR|ArCADE|VR|CDDA|PAD|MiDi|CoBaLT|DiSCOVER)\b", "");
            name = Regex.Replace(name, @"\b(WareZ Audio info|Kontakt|Audiostrike|SYNTHiC4TE|AUDIOXiMiK|MAGNETRiXX|TZ7iSO|KLI|DVDriSO|DVD9|KRock|ACiD|REX|RMX|SynthX|AiFF|Apple Loops|AiRISO|MULTiFORMAT|AudioP2P|GHOSTiSO|REX2|DXi|HYBRiD|AKAI|ALFiSO)\b", "", RegexOptions.IgnoreCase);
            //name = Regex.Replace(name, "(HYBRID|DYNAMiCS|PROPER|VSTi|RTAS|CHAOS|AMPLiFY| AU |MATRiX)", "");
            //name = Regex.Replace(name, "(WareZ Audio info|Kontakt|Audiostrike|SYNTHiC4TE|AUDIOXiMiK||MAGNETRiXX)", "", RegexOptions.IgnoreCase);
            name = Regex.Replace(name, @"  +", " ");
            name = name.Trim(' ', '-');
            var destPath = $"{destFolder}\\{name}{extraPath}";

            CopyFiles(folder, destPath, canMove, false);
        }
        public async Task <FileSystemResult <IFile> > CreateAssetAsync(string name, Stream readstream, CancellationToken token, IProgress <FileProgress> progress, Dictionary <string, object> properties)
        {
            string ext = Path.GetExtension(name);

            if ((ext != "png") && (ext != "jpg") && (ext != "jpeg") && (ext != "gif"))
            {
                return(new FileSystemResult <IFile>("Google Drive only supports 'thumbnail' asset, acceptable formats are, jpg, png and gif"));
            }
            string mime;

            switch (ext)
            {
            case "png":
                mime = "image/png";
                break;

            case "jpeg":
            case "jpg":
                mime = "image/jpeg";
                break;

            default:
                mime = "image/gif";
                break;
            }
            MemoryStream ms = new MemoryStream();
            await readstream.CopyToAsync(ms, 16384, token);

            MemoryFile file = new MemoryFile(FullName + ":thumbnail", "thumbnail", mime, ms.ToArray());
            File       f    = new File {
                Thumbnail = new File.ThumbnailData {
                    MimeType = mime, Image = Convert.ToBase64String(ms.ToArray())
                }
            };
            string url = GooglePatch.FormatRest(Id);
            FileSystemResult <string> ex = await FS.OAuth.CreateMetadataStream <string>(url, Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(f)), "application/json", new HttpMethod("PATCH"));

            if (!ex.IsOk)
            {
                return(new FileSystemResult <IFile>(ex.Error));
            }
            Assets.Clear();
            Assets.Add(file);
            return(new FileSystemResult <IFile>(file));
        }
        // clean all files and directories in iPath, then delete iPath dir...
        public static void DeleteDirectory(string iPath, string[] ignoreFiles = null)
        {
            if (iPath == null)
            {
                return;
            }
            if (Application.platform == RuntimePlatform.WindowsEditor)
            {
                iPath = iPath.Replace('/', '\\');
            }

            if (!Directory.Exists(iPath))
            {
                return;
            }

            // delete subDir
            string[] dirPaths = Directory.GetDirectories(iPath);
            for (int i = 0; i < dirPaths.Length; i++)
            {
                DeleteDirectory(dirPaths[i], ignoreFiles);
            }

            // delete files
            string[] filePaths = Directory.GetFiles(iPath);
            for (int i = 0; i < filePaths.Length; ++i)
            {
                string extension = Path.GetExtension(filePaths[i]);
                if (ignoreFiles != null && Array.IndexOf(ignoreFiles, extension) >= 0)
                {
                    continue;
                }
                if (filePaths[i] != null)
                {
                    File.Delete(filePaths[i]);
                }
            }

            // delete iPath dir...
            if (Directory.GetDirectories(iPath).Length == 0 && Directory.GetFiles(iPath).Length == 0)
            {
                Directory.Delete(iPath);
            }
        }
Beispiel #10
0
 static void CopyFiles(string source, string dest, bool move, bool includeArchives = true)
 {
     if (move)
     {
         MarkFolderWritable(source);
     }
     MarkFolderWritable(dest);
     Console.WriteLine("{0} {1} => {2}", move ? "Moving" : "Copying", source, dest);
     source = source.TrimEnd('\\');
     dest   = dest.TrimEnd('\\');
     if (!Directory.Exists(dest))
     {
         Directory.CreateDirectory(dest);
     }
     Directory.EnumerateDirectories(source, "*", SearchOption.AllDirectories).Select(d => d.Replace(source, dest)).ForEach(path => Directory.CreateDirectory(path));
     foreach (var file in Directory.EnumerateFiles(source, "*", SearchOption.AllDirectories).Where(f => Path.GetExtension(f) != ".nfo" && !Regex.IsMatch(Path.GetFileName(f), "All.Collection.Upload|WareZ-Audio", RegexOptions.IgnoreCase)).ToArray())
     {
         if (Path.GetExtension(file) == ".sfv")
         {
             continue;
         }
         //if (!includeArchives && Regex.IsMatch(Path.GetExtension(file), @"\.(rar|r\d+|zip|iso)"))
         if (!includeArchives && Path.GetDirectoryName(file) == source && Regex.IsMatch(Path.GetExtension(file), @"\.(rar|r\d+|zip)"))
         {
             continue;
         }
         var newFile = file.Replace(source, dest);
         if (move)
         {
             if (File.Exists(newFile))
             {
                 File.Delete(newFile);
             }
             File.Move(file, newFile);
         }
         else
         {
             File.Copy(file, newFile, true);
         }
     }
 }
Beispiel #11
0
        static IEnumerable <string> GetAssociatedArchives(string file, IEnumerable <string> files)
        {
            string pattern;

            if (file.EndsWith(".part1.rar"))
            {
                pattern = EscapeSpecialChars(file.Substring(0, file.Length - 10)) + @"\.part\d+.rar";
            }
            else if (file.EndsWith(".part01.rar"))
            {
                pattern = EscapeSpecialChars(file.Substring(0, file.Length - 11)) + @"\.part\d+.rar";
            }
            else if (Path.GetExtension(file) == ".r00")
            {
                pattern = EscapeSpecialChars(file.Substring(0, file.Length - 4)) + @"\.r\d+";
            }
            else
            {
                return new[] { file }
            };
            return(files.Where(f => Regex.IsMatch(f, pattern, RegexOptions.IgnoreCase)));
        }
Beispiel #12
0
        public IEnumerable <string> GetEmbeddedFiles()
        {
            MsgReader.Reader reader = new MsgReader.Reader();

            string tempMsgFilePath = GetTempLocalFile();

            DirectoryInfo tempDirectory       = new DirectoryInfo(Path.GetTempPath());
            DirectoryInfo tempOutputDirectory = tempDirectory.CreateSubdirectory(Guid.NewGuid().ToString());

            reader.ExtractToFolder(tempMsgFilePath, tempOutputDirectory.FullName);

            List <string> tempFiles = new List <string>();

            foreach (FileInfo file in tempOutputDirectory.EnumerateFiles())
            {
                //HTM files will be the email itself, which is covered by reading contents
                //DB files are to exclude thumbs.db files
                if (file.Extension.ToUpper() != ".HTM" &&
                    file.Extension.ToUpper() != ".DB")
                {
                    string thisTempFile = tempDirectory +
                                          Guid.NewGuid().ToString() +
                                          Path.GetExtension(file.Name);

                    File.Copy(file.FullName, thisTempFile);

                    tempFiles.Add(thisTempFile);
                }
            }

            try
            {
                File.Delete(tempMsgFilePath);
                tempOutputDirectory.Delete(true);
            }
            catch (Exception) { }

            return(tempFiles);
        }
Beispiel #13
0
        static IEnumerable <string> GetArchiveFiles(string[] files)
        {
            var results = new List <string>();

            foreach (var file in files)
            {
                if (/*Path.GetExtension(file) == ".iso" || */ Path.GetExtension(file) == ".zip")                 // Any iso or zip file.
                {
                    results.Add(file);
                }
                //if (Path.GetExtension(file) == ".nrg")
                //    results.Add(file);
                if (Path.GetExtension(file) == ".r00" && files.All(f => String.Compare(f, file.Substring(0, file.Length - 4) + ".rar", StringComparison.OrdinalIgnoreCase) != 0)) // Any .r00 file that doesn't have a corresponding .rar file.
                {
                    results.Add(file);
                }
                if (Path.GetExtension(file) == ".rar" && (!Regex.IsMatch(file, @"(?i)part[0-9]+\.rar$") || Regex.IsMatch(file, @"(?i)part0*1\.rar$")))                 // Any rar file doesn't end with partxxx.rar, unless its the first part.
                {
                    results.Add(file);
                }
            }
            return(results.ToArray());
        }
Beispiel #14
0
 public static string GetExtension(string path)
 {
     return(Path.GetExtension(path));
 }
Beispiel #15
0
 public string GetFileExtension(string fileName)
 {
     return(Path.GetExtension(fileName));
 }
        // ReSharper disable once CyclomaticComplexity
        internal async Task <FileSystemResult <IFile> > InternalCreateFile(string name, string type, bool overwrite, AmazonObject parent, Stream readstream, CancellationToken token, IProgress <FileProgress> progress, Dictionary <string, object> properties)
        {
            if (readstream.Length == 0)
            {
                throw new ArgumentException("input stream must have length");
            }
            string url = AmazonUpload.FormatRest(FS.OAuth.EndPoint.ContentUrl, "?suppress=deduplication");

            Json.Metadata j = null;
            if (!overwrite)
            {
                if (properties == null)
                {
                    properties = new Dictionary <string, object>();
                }
                j                             = new Json.Metadata();
                j.version                     = 0;
                j.contentProperties           = new Json.ContentProperties();
                j.contentProperties.size      = readstream.Length;
                j.contentProperties.version   = 0;
                j.contentProperties.extension = Path.GetExtension(name);
                string n = Extensions.ContentFromExtension(j.contentProperties.extension);
                j.contentProperties.contentType = !string.IsNullOrEmpty(n) ? n : "application/octet-stream";
                if (properties.Any(a => a.Key.Equals("ModifiedDate", StringComparison.InvariantCultureIgnoreCase)))
                {
                    j.modifiedDate =
                        (DateTime)
                        properties.First(
                            a => a.Key.Equals("ModifiedDate", StringComparison.InvariantCultureIgnoreCase)).Value;
                }
                if (properties.Any(a => a.Key.Equals("CreatedDate", StringComparison.InvariantCultureIgnoreCase)))
                {
                    j.createdDate =
                        (DateTime)
                        properties.First(
                            a => a.Key.Equals("CreatedDate", StringComparison.InvariantCultureIgnoreCase)).Value;
                }
                if (properties.Any(a => a.Key.Equals("Application", StringComparison.InvariantCultureIgnoreCase)))
                {
                    j.createdBy =
                        (string)
                        properties.First(
                            a => a.Key.Equals("Application", StringComparison.InvariantCultureIgnoreCase)).Value;
                }
                else
                {
                    j.createdBy = "CloudFileSystem";
                }
                if (properties.Any(a => a.Key.Equals("MD5", StringComparison.InvariantCultureIgnoreCase)))
                {
                    j.contentProperties.md5 =
                        (string)
                        properties.First(a => a.Key.Equals("MD5", StringComparison.InvariantCultureIgnoreCase))
                        .Value;
                }
                j.description = j.name = name;
                j.isShared    = false;
                j.kind        = type;
                j.parents     = new List <string>();
                j.parents.Add(parent.Id);
            }
            HttpRequestMessage msg      = new HttpRequestMessage(overwrite ? HttpMethod.Put : HttpMethod.Post, url);
            string             boundary = "--" + Guid.NewGuid().ToString();

            msg.Headers.UserAgent.ParseAdd(FS.OAuth.UserAgent);
            MultipartFormDataContent ct = new MultipartFormDataContent(boundary);

            if (!overwrite)
            {
                string        meta = JsonConvert.SerializeObject(j);
                StringContent sc   = new StringContent(meta, Encoding.UTF8);
                ct.Add(sc, "metadata");
            }
            StreamContent ssc = new StreamContent(readstream);

            ct.Add(ssc, "file", name);
            msg.Content = ct;
            HttpClientHandler      handler         = new HttpClientHandler();
            ProgressMessageHandler progresshandler = new ProgressMessageHandler(handler);

            progresshandler.HttpSendProgress += (a, b) =>
            {
                FileProgress u = new FileProgress();
                u.Percentage   = b.ProgressPercentage;
                u.TotalSize    = b.TotalBytes ?? 0;
                u.TransferSize = b.BytesTransferred;
                progress.Report(u);
            };
            handler.AllowAutoRedirect      = true;
            handler.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
            await FS.CheckExpirations();

            HttpClient          cl       = new HttpClient(progresshandler);
            HttpResponseMessage response = null;

            try
            {
                response = await cl.SendAsync(msg, token);

                if (response.StatusCode == HttpStatusCode.Created)
                {
                    string dd = await response.Content.ReadAsStringAsync();

                    string          parentpath = string.Empty;
                    AmazonDirectory dir        = parent as AmazonDirectory;
                    if (dir == null || !dir.IsRoot)
                    {
                        parentpath = FullName;
                    }
                    AmazonFile file = new AmazonFile(parentpath, FS)
                    {
                        Parent = dir
                    };
                    file.SetData(dd);
                    progress.Report(new FileProgress
                    {
                        Percentage   = 100,
                        TotalSize    = file.Size,
                        TransferSize = file.Size
                    });
                    return(new FileSystemResult <IFile>(file));
                }
                return(new FileSystemResult <IFile>("Http Error : " + response.StatusCode));
            }
            catch (Exception e)
            {
                return(new FileSystemResult <IFile>("Exception Error : " + e.Message));
            }
            finally
            {
                response?.Dispose();
                cl?.Dispose();
                handler?.Dispose();
                progresshandler?.Dispose();
                msg?.Dispose();
            }
        }
Beispiel #17
0
        public void TestGetRecursiveFilesWithSubsetSearch()
        {
            var tempLongPathFilename = Path.Combine(uncDirectory, Path.GetRandomFileName());

            Directory.CreateDirectory(tempLongPathFilename);
            try
            {
                Assert.IsTrue(Directory.Exists(tempLongPathFilename));
                var randomFileName = Util.CreateNewEmptyFile(tempLongPathFilename);

                var searchPattern = Path.GetFileName(randomFileName).Substring(0, 3) + "*" + Path.GetExtension(randomFileName);

                var files = Directory.GetFiles(uncDirectory, searchPattern, SearchOption.AllDirectories).ToArray();
                Assert.AreEqual(1, files.Length);
                Assert.IsFalse(files.Contains(uncFilePath));
                Assert.IsTrue(files.Contains(randomFileName));
            }
            finally
            {
                const bool recursive = true;
                Directory.Delete(tempLongPathFilename, recursive);
            }
        }
Beispiel #18
0
        public List <Stream> GetStreams(string filename)
        {
            string ext = Path.GetExtension(filename);

            if (string.IsNullOrEmpty(ext))
            {
                return(null);
            }
            ext = ext.Replace(".", string.Empty).ToLower();
            string name = Path.GetFileNameWithoutExtension(filename);

            if (string.IsNullOrEmpty(name))
            {
                return(null);
            }
            Regex           lm       = new Regex(".+\\.([^\\.]+)$", RegexOptions.Singleline);
            MatchCollection col      = lm.Matches(name);
            string          language = "xx";

            foreach (Match m in col)
            {
                if (m.Success)
                {
                    string val = m.Groups[1].Value.ToLower();
                    if (SubtitleHelper.Iso639_3_TO_Iso639_1.ContainsKey(val))
                    {
                        language = SubtitleHelper.Iso639_3_TO_Iso639_1[val];
                        break;
                    }
                    if (SubtitleHelper.Iso639_1_TO_Languages.ContainsKey(val))
                    {
                        language = val;
                        break;
                    }
                    if (SubtitleHelper.Languages_TO_ISO639_1_Lower.ContainsKey(val))
                    {
                        language = SubtitleHelper.Languages_TO_ISO639_1_Lower[val];
                        break;
                    }
                }
            }
            string format = null;

            if ((ext == "txt") || (ext == "sub"))
            {
                string[] lines     = File.ReadAllLines(filename);
                string   firstline = null;
                foreach (string ws in lines)
                {
                    string k = ws.Trim();
                    if (!string.IsNullOrEmpty(k))
                    {
                        firstline = k;
                        break;
                    }
                }
                if (firstline != null)
                {
                    lm = new Regex("^\\{[0-9]+\\}\\{[0-9]*\\}", RegexOptions.Singleline);
                    Match m = lm.Match(firstline);
                    if (m.Success)
                    {
                        format = "microdvd";
                    }
                    else
                    {
                        lm = new Regex("^[0-9]{1,2}:[0-9]{2}:[0-9]{2}[:=,]", RegexOptions.Singleline);
                        m  = lm.Match(firstline);
                        if (m.Success)
                        {
                            format = "txt";
                        }
                        else
                        {
                            if (firstline.Contains("[SUBTITLE]"))
                            {
                                format = "subviewer";
                            }
                        }
                    }
                }
            }
            ext = ext.Replace("ass", "ssa");
            if (format == null)
            {
                format = ext;
            }
            Stream s = new Stream();

            s.Format       = format;
            s.StreamType   = "3";
            s.File         = filename;
            s.LanguageCode = SubtitleHelper.Iso639_1_TO_Iso639_3[language];
            s.Language     = SubtitleHelper.Iso639_1_TO_Languages[language];
            List <Stream> sts = new List <Stream>();

            sts.Add(s);
            return(sts);
        }
Beispiel #19
0
        public List <Stream> GetStreams(IFile file)
        {
            string ext = Path.GetExtension(file.Name);

            if (string.IsNullOrEmpty(ext))
            {
                return(null);
            }
            ext = ext.Replace(".", string.Empty).ToLower();
            string name = Path.GetFileNameWithoutExtension(file.Name);

            if (string.IsNullOrEmpty(name))
            {
                return(null);
            }
            Regex           lm       = new Regex(".+\\.([^\\.]+)$", RegexOptions.Singleline);
            MatchCollection col      = lm.Matches(name);
            string          language = "xx";

            foreach (Match m in col)
            {
                if (m.Success)
                {
                    string val = m.Groups[1].Value.ToLower();
                    if (SubtitleHelper.Iso639_3_TO_Iso639_1.ContainsKey(val))
                    {
                        language = SubtitleHelper.Iso639_3_TO_Iso639_1[val];
                        break;
                    }
                    if (SubtitleHelper.Iso639_1_TO_Languages.ContainsKey(val))
                    {
                        language = val;
                        break;
                    }
                    if (SubtitleHelper.Languages_TO_ISO639_1_Lower.ContainsKey(val))
                    {
                        language = SubtitleHelper.Languages_TO_ISO639_1_Lower[val];
                        break;
                    }
                }
            }
            string        format = null;
            List <Stream> sts    = new List <Stream>();

            if ((ext == "txt") || (ext == "sub"))
            {
                FileSystemResult <System.IO.Stream> res = file.OpenRead();
                if (res == null || !res.IsOk)
                {
                    return(sts);
                }
                List <string> lines  = new List <string>();
                StreamReader  reader = new StreamReader(res.Result);
                while (!reader.EndOfStream)
                {
                    lines.Add(reader.ReadLine());
                }
                string firstline = null;
                foreach (string ws in lines)
                {
                    string k = ws.Trim();
                    if (!string.IsNullOrEmpty(k))
                    {
                        firstline = k;
                        break;
                    }
                }
                if (firstline != null)
                {
                    lm = new Regex("^\\{[0-9]+\\}\\{[0-9]*\\}", RegexOptions.Singleline);
                    Match m = lm.Match(firstline);
                    if (m.Success)
                    {
                        format = "microdvd";
                    }
                    else
                    {
                        lm = new Regex("^[0-9]{1,2}:[0-9]{2}:[0-9]{2}[:=,]", RegexOptions.Singleline);
                        m  = lm.Match(firstline);
                        if (m.Success)
                        {
                            format = "txt";
                        }
                        else
                        {
                            if (firstline.Contains("[SUBTITLE]"))
                            {
                                format = "subviewer";
                            }
                        }
                    }
                }
            }
            ext = ext.Replace("ass", "ssa");
            if (format == null)
            {
                format = ext;
            }
            Stream s = new Stream
            {
                Format       = format,
                StreamType   = "3",
                File         = file.FullName,
                LanguageCode = SubtitleHelper.Iso639_1_TO_Iso639_3[language],
                Language     = SubtitleHelper.Iso639_1_TO_Languages[language]
            };

            sts.Add(s);
            return(sts);
        }