コード例 #1
0
ファイル: Util.cs プロジェクト: hkusoft/SmartUnpack
        /// <summary>
        ///
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="ToRecyclerBin">By default, directly remove the file.</param>
        /// <returns></returns>
        public static bool DeleteFile(string filePath, out string resultMessage, bool ToRecyclerBin = false)
        {
            bool bSuccess = false;

            try
            {
                var name = Path.GetFileName(filePath);
                resultMessage = $"File clean up: Removing {name}";

                if (ToRecyclerBin)
                {
                    FileSystem.DeleteFile(filePath, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin);
                }
                else
                {
                    File.Delete(filePath);
                }

                bSuccess = true;
            }
            catch (Exception ex)
            {
                resultMessage = $"Exception: {ex.Message}";
                return(false);
            }
            return(bSuccess);
        }
コード例 #2
0
ファイル: BenRunner.cs プロジェクト: wbernest/BenDownloader
        private List <BenRecord> GetFileList()
        {
            List <BenRecord> downloadList = new List <BenRecord>();
            string           dirFile      = m_tempDirectoryName + "bendir.txt";

            try
            {
                //delete the existing dir file if one exists.
                if (FileSystem.FileExists(dirFile))
                {
                    FileSystem.DeleteFile(dirFile);
                }

                //build new dir files.
                BuildBenLinkDirINI();

                ExecBenCommand();

                // build list of records to download
                if (FileSystem.FileExists(dirFile))
                {
                    TextFieldParser dirReader = FileSystem.OpenTextFieldParser(dirFile, new string[] { "\t" });
                    while (!dirReader.EndOfData)
                    {
                        string[] curRow = dirReader.ReadFields();

                        if (Convert.ToInt32(curRow[2]) < BENMAXFILESIZE)
                        {
                            BenRecord curRecord = new BenRecord(Convert.ToInt32(curRow[0]), Convert.ToDateTime(curRow[1]), Convert.ToInt32(curRow[2]));

                            if (curRecord.DateTime > DateTime.UtcNow.AddDays(-30) && curRecord.DateTime > m_lastFileDownloaded.DateTime)
                            {
                                downloadList.Add(curRecord);
                            }
                        }
                        else
                        {
                            Program.Log("File too large Error: " + m_siteName + " - " + Convert.ToString(curRow[0]), m_tempDirectoryName);
                        }
                    }
                    dirReader.Close();
                }
                else
                {
                    throw new Exception("GetFileList Error: " + m_siteName + " - dir file does not exist.");
                }
            }
            catch (Exception ex)
            {
                Program.Log("GetFileList Error: " + m_siteName + " - " + ex.ToString(), m_tempDirectoryName);
                throw new Exception("GetFileList Error: " + m_siteName + " - " + ex.ToString());
            }
            return(downloadList);
        }
コード例 #3
0
ファイル: BenRunner.cs プロジェクト: wbernest/BenDownloader
        private void BuildBenLinkDLINI(List <BenRecord> fileList)
        {
            string requestfilename = m_tempDirectoryName + "benlink.req";

            string myINIFile = "[Signature]" + System.Environment.NewLine +
                               "Program=BenLink" + System.Environment.NewLine +
                               "FileType=Request" + System.Environment.NewLine +
                               "FileVersion=1" + System.Environment.NewLine +
                               System.Environment.NewLine +
                               "[General]" + System.Environment.NewLine +
                               "NbRequest=" + fileList.Count.ToString() + System.Environment.NewLine +
                               System.Environment.NewLine +
                               "[Device]" + System.Environment.NewLine +
                               "DeviceType=5" + System.Environment.NewLine +
                               "DeviceSN=" + m_serialNumber + System.Environment.NewLine +
                               "NominalFrequency=60" + System.Environment.NewLine +
                               "DataDirectory=" + m_tempDirectoryName + System.Environment.NewLine +
                               System.Environment.NewLine +
                               "CommAddress=1" + System.Environment.NewLine +
                               "[ConnectionParam]" + System.Environment.NewLine +
                               "AccessType=0" + System.Environment.NewLine +
                               "UserName=0" + System.Environment.NewLine +
                               "IPAddress=" + m_ipAddress + System.Environment.NewLine +
                               "HangupTimeout=0";

            int i = 1;

            foreach (BenRecord currec in fileList)
            {
                myINIFile += System.Environment.NewLine + System.Environment.NewLine + System.Environment.NewLine + "[Request" + i++ + "]" + System.Environment.NewLine +
                             "RequestType=2" + System.Environment.NewLine +
                             "RecordNum=" + currec.Id + System.Environment.NewLine +
                             "SubBenNum=0" + System.Environment.NewLine +
                             "Origin=1" + System.Environment.NewLine +
                             "OptionFlags=2" + System.Environment.NewLine +
                             "DataPath=" + m_tempDirectoryName + System.Environment.NewLine +
                             "FileName=" + Get232Fn(currec.DateTime, currec.Id.ToString());
            }


            try
            {
                System.IO.FileInfo file = new System.IO.FileInfo(requestfilename);
                file.Directory.Create();
                FileSystem.WriteAllText(file.FullName, myINIFile, false, System.Text.Encoding.ASCII);
            }
            catch (Exception ex)
            {
                Program.Log("BuildBenLinkDLINI error: " + m_siteName + " - " + ex.ToString(), m_tempDirectoryName);

                throw new System.Exception("BuildBenLinkDLINI error: " + m_siteName + " - " + ex.ToString());
            }
        }
コード例 #4
0
        private void renameProfile_btn_Click(object sender, EventArgs e)
        {
            DialogResult res;

            res = MessageBox.Show("Are you sure you want to delete the \"" + profile + "\" profile? You cannot undo this action! All mods contained in it will be completly deleted without recover options!", "Delete profile", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (res == DialogResult.Yes)
            {
                FileSystem.DeleteDirectory(Application.StartupPath + "/Profiles/" + profile, DeleteDirectoryOption.DeleteAllContents);
                Application.Restart();
                Environment.Exit(0);
            }
        }
コード例 #5
0
ファイル: BenRunner-old.cs プロジェクト: lulzzz/openMIC
        private List <BenRecord> GetFileList()
        {
            List <BenRecord> downloadList = new List <BenRecord>();
            string           dirFile      = localPath + "\\bendir.txt";

            try
            {
                //delete the existing dir file if one exists.
                //if (FileSystem.FileExists(dirFile))
                //    FileSystem.DeleteFile(dirFile);

                //build new dir files.
                BuildBenLinkDirINI();

                ExecBenCommand();

                // build list of records to download
                // todo: build an algroithm for rollover of record numbers
                if (FileSystem.FileExists(dirFile))
                {
                    TextFieldParser dirReader = FileSystem.OpenTextFieldParser(dirFile, new string[] { "\t" });
                    string[]        curRow;
                    while (!dirReader.EndOfData)
                    {
                        curRow = dirReader.ReadFields();

                        if (Convert.ToInt32(curRow[2]) < BENMAXFILESIZE)
                        {
                            //Program.Log("DateTime from GetFile List for "+Convert.ToInt32(curRow[0]).ToString() +": " + Convert.ToDateTime(curRow[1]).ToString());
                            BenRecord curRecord = new BenRecord(Convert.ToInt32(curRow[0]), Convert.ToDateTime(curRow[1]), Convert.ToInt32(curRow[2]));
                            downloadList.Add(curRecord);
                        }
                        else
                        {
                            SendFileTooLargeEmailNotification("Record id: " + curRow[0]);
                        }
                    }
                    dirReader.Close();
                }
                else
                {
                    throw new Exception("GetFileList Error: " + siteName + " - dir file does not exist.");
                }
            }
            catch (Exception ex)
            {
                Program.Log("GetFileList Error: " + siteName + " - " + ex.ToString());

                throw new Exception("GetFileList Error: " + siteName + " - " + ex.ToString());
            }
            return(downloadList);
        }
コード例 #6
0
ファイル: BenRunner.cs プロジェクト: wbernest/BenDownloader
        private bool ExecBenCommand()
        {
            int exitcode = -1;

            try
            {
                string   benLinCmdLine = Program.OpenMiConfigurationFile.Settings["systemSettings"]["BenLinkCommandLine"].Value;
                string   cmdLine       = benLinCmdLine.Replace("xxx", GetShortPath(m_tempDirectoryName));
                string[] cmdLineSplit  = cmdLine.Split(new char[] { ' ' }, 2);
                var      psi           = new ProcessStartInfo(cmdLineSplit[0])
                {
                    Arguments       = cmdLineSplit[1],
                    UseShellExecute = false,
                    CreateNoWindow  = true
                };

                if (m_fileWatcher.EnableRaisingEvents)
                {
                    m_lastFileChangedTime     = DateTime.UtcNow.Ticks;
                    m_activityMonitor.Enabled = true;
                }

                // ReSharper disable once PossibleNullReferenceException
                using (m_process = Process.Start(psi))
                {
                    m_process.WaitForExit();
                    exitcode = m_process.ExitCode;
                }

                FileSystem.DeleteFile(m_tempDirectoryName + "benlink.req");
                if (File.Exists(m_tempDirectoryName + "benlink.rsp"))
                {
                    FileSystem.DeleteFile(m_tempDirectoryName + "benlink.rsp");
                }
            }
            catch (Exception ex)
            {
                Program.Log("ExecBenCommand error: " + m_siteName + " - " + ex.ToString(), m_tempDirectoryName);

                throw new Exception("ExecBenCommand error: " + m_siteName + " - " + ex.ToString());
            }
            finally
            {
                m_activityMonitor.Enabled = false;
            }

            return(exitcode == 0);
        }
コード例 #7
0
ファイル: BenRunner-old.cs プロジェクト: lulzzz/openMIC
        private void BuildBenLinkDirINI()
        {
            string requestFileName = localPath + "\\benlink.req";

            string myINIFile = "[Signature]" + System.Environment.NewLine +
                               "Program=BenLink" + System.Environment.NewLine +
                               "FileType=Request" + System.Environment.NewLine +
                               "FileVersion=1" + System.Environment.NewLine +
                               System.Environment.NewLine +
                               "[General]" + System.Environment.NewLine +
                               "NbRequest=1" + System.Environment.NewLine +
                               System.Environment.NewLine +
                               "[Device]" + System.Environment.NewLine +
                               "DeviceType=5" + System.Environment.NewLine +
                               "DeviceSN=" + serialNumber + System.Environment.NewLine +
                               "NominalFrequency=60" + System.Environment.NewLine +
                               "DataDirectory=" + localPath + '\\' + System.Environment.NewLine +
                               System.Environment.NewLine +
                               "[ConnectionParam]" + System.Environment.NewLine +
                               "AccessType=0" + System.Environment.NewLine +
                               "UserName=0" + System.Environment.NewLine +
                               "CommAddress=1" + System.Environment.NewLine +
                               "IPAddress=" + ipAddress + System.Environment.NewLine +
                               "HangupTimeout=0" + System.Environment.NewLine +
                               System.Environment.NewLine +
                               "[Request1]" + System.Environment.NewLine +
                               "RequestType=1" + System.Environment.NewLine +
                               "Origin=1" + System.Environment.NewLine +
                               "SubBens=1" + System.Environment.NewLine +
                               "DataPath=" + localPath;

            try
            {
                System.IO.FileInfo file = new System.IO.FileInfo(requestFileName);
                file.Directory.Create();
                FileSystem.WriteAllText(file.FullName, myINIFile, false, System.Text.Encoding.ASCII);
            }
            catch (Exception ex)
            {
                Program.Log("BuildBenLinkDirINI error: " + siteName + '-' + ex.ToString());

                throw new SystemException("BuildBenLinkDirINI error: " + siteName + '-' + ex.ToString());
            }
        }
コード例 #8
0
    private void olvModList_DragDrop(object sender, DragEventArgs e)
    {
        string modCacheFolder = Serializer.GetModsCacheFolder();

        Directory.CreateDirectory(modCacheFolder);

        var files = e.Data.GetData(DataFormats.FileDrop) as string[];

        if (files.Length == 0)
        {
            return;
        }

        string[] modFiles  = Directory.GetFiles(modCacheFolder, "*", SearchOption.AllDirectories);
        string   lastAdded = null;


        foreach (string file in files)
        {
            bool   isDir    = Directory.Exists(file);
            string fileName = Path.GetFileName(file);

            if (isDir)
            {
                FileSystem.MoveDirectory(file, modCacheFolder + fileName, UIOption.OnlyErrorDialogs, UICancelOption.DoNothing);
            }
            else
            {
                if (!modFiles.Contains(file) && !File.Exists(modCacheFolder + fileName) && File.Exists(file))
                {
                    File.Move(file, modCacheFolder + fileName);
                }
                lastAdded = modCacheFolder + fileName;
            }
        }

        ModCache.RescanModCacheFolder();

        if (lastAdded != null)
        {
            olvModList.SelectedObject = modsData.modInfos.FindLast(x => x.modPath.ToLower() == lastAdded.ToLower());
            olvModList.EnsureModelVisible(olvModList.SelectedObject);
        }
    }
コード例 #9
0
        private static void DeleteFilesOrDirectories(string filePath)
        {
            try
            {
                var dir = Path.GetDirectoryName(filePath);
                if (dir == null)
                {
                    return;
                }

                var files = Directory.EnumerateFiles(dir).Where(HelperFunctions.IsVideo).ToList();

                if (filePath != Xml.Location)
                {
                    if (files.All(f => f == filePath) && dir != Xml.Location.Substring(0, Xml.Location.Length - 1))
                    {
                        FileSystem.DeleteDirectory(dir, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin);
                    }
                    else
                    {
                        FileSystem.DeleteFile(filePath, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin);
                    }
                }
                else
                {
                    // Delete empty directories
                    var allDirectories  = Directory.EnumerateDirectories(filePath).ToList();
                    var fileDirectories = files.Select(Path.GetDirectoryName).ToList();
                    foreach (var directory in allDirectories.Where(directory => !fileDirectories.Contains(directory)))
                    {
                        FileSystem.DeleteDirectory(directory, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin);
                    }
                }
            }
            catch (IOException ex)
            {
                LogFile.Log(ex.ToString());
            }
        }
コード例 #10
0
ファイル: BenRunner-old.cs プロジェクト: lulzzz/openMIC
 private void FixCFGFiles(List <BenRecord> fileList)
 {
     try
     {
         string curFileName;
         string curFileContent;
         foreach (BenRecord curRec in fileList)
         {
             curFileName = localPath + "\\" + get232FN(curRec.rDateTime, serialNumber) + ".cfg";
             if (FileSystem.FileExists(curFileName))
             {
                 curFileContent = FileSystem.ReadAllText(curFileName);
                 FileSystem.WriteAllText(curFileName, siteName + curFileContent, false, System.Text.Encoding.ASCII);
             }
         }
     }
     catch (Exception ex)
     {
         Program.Log("fixcfgFiles error: " + siteName + " - " + ex.ToString());
         throw new System.Exception("fixcfgFiles error: " + siteName + " - " + ex.ToString());
     }
 }
コード例 #11
0
ファイル: BenRunner-old.cs プロジェクト: lulzzz/openMIC
        private void ExecBenCommand()
        {
            try
            {
                string   benLinCmdLine = ConfigurationFile.Current.Settings["systemSettings"]["BenLinkCommandLine"].Value;
                string   cmdLine       = benLinCmdLine.Replace("xxx", GetShortPath(localPath));
                string[] cmdLineSplit  = cmdLine.Split(new char[] { ' ' }, 2);
                var      psi           = new ProcessStartInfo(cmdLineSplit[0])
                {
                    Arguments       = cmdLineSplit[1],
                    UseShellExecute = false,
                    CreateNoWindow  = true
                };

                bool flag = true;
                while (flag)
                {
                    using (Process p = Process.Start(psi))
                    {
                        p.WaitForExit();

                        if (p.ExitCode == 0)
                        {
                            flag = false;
                        }
                    }
                }

                FileSystem.DeleteFile(localPath + "\\benlink.req");
                FileSystem.DeleteFile(localPath + "\\benlink.rsp");
                UpdateTimestamps();
            }
            catch (Exception ex)
            {
                Program.Log("ExecBenCommand error: " + siteName + " - " + ex.ToString());

                throw new Exception("ExecBenCommand error: " + siteName + " - " + ex.ToString());
            }
        }
コード例 #12
0
ファイル: BenRunner.cs プロジェクト: wbernest/BenDownloader
        private void XferDataFiles()
        {
            List <BenRecord> myFiles = GetFileList();

            try
            {
                int numFiles = myFiles.Count;

                if (myFiles.Any())
                {
                    //if there are less than 25 records to download then begin downloading files
                    if (numFiles + 50 < MAXFILELIMIT)
                    {
                        BuildBenLinkDLINI(myFiles);

                        m_fileWatcher.EnableRaisingEvents = true;
                        ExecBenCommand();
                        m_fileWatcher.EnableRaisingEvents = false;

                        UpdateTimestamps();
                    }
                    else
                    {
                        throw new System.Exception("Site " + m_siteName + " has too many files, aborting download.");
                    }
                }
            }
            catch (Exception ex)
            {
                Program.Log("XFER Error/Site: " + m_siteName + " - " + ex.ToString(), m_tempDirectoryName);

                throw new System.Exception("XFER Error/Site: " + m_siteName + " - " + ex.ToString());
            }
            finally
            {
                FileSystem.DeleteFile(m_tempDirectoryName + "bendir.txt");
            }
        }
コード例 #13
0
ファイル: BenRunner-old.cs プロジェクト: lulzzz/openMIC
        private void XferDataFiles()
        {
            List <BenRecord> myFiles = GetFileList();
            int curRecId             = downloadFileNumber;

            try
            {
                int numFiles = myFiles.Count;

                if (numFiles > 0)
                {
                    //if there are less than 25 records to download then begin downloading files
                    if (numFiles + 50 < MAXFILELIMIT)
                    {
                        BuildBenLinkDLINI(myFiles);
                        ExecBenCommand();
                        FixCFGFiles(myFiles);
                        curRecId = myFiles[0].rId;
                    }
                    else
                    {
                        SendTooManyFilesEmailNotification(numFiles);
                        throw new System.Exception("Site " + siteName + " has too many files, aborting download.");
                    }
                }
            }
            catch (Exception ex)
            {
                Program.Log("XFER Error/Site: " + siteName + " - " + ex.ToString());

                throw new System.Exception("XFER Error/Site: " + siteName + " - " + ex.ToString());
            }
            finally
            {
                //lastFileDownloaded = curRecId.ToString();
                FileSystem.DeleteFile(localPath + "\\bendir.txt");
            }
        }
コード例 #14
0
        private void delete_Click(object sender, EventArgs e)
        {
            var t = (TreeViewModel)Videos.SelectedItem;

            FileSystem.DeleteFile(t.FullPath, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin);
        }
コード例 #15
0
        public void Execute()
        {
            string path;

            using (var inputStream = _fileSystem.File.OpenRead(_file))
            {
                var decoder = BitmapDecoder.Create(
                    inputStream,
                    BitmapCreateOptions.PreservePixelFormat,
                    BitmapCacheOption.None);

                var containerFormat = decoder.CodecInfo.ContainerFormat;

                var encoder = CreateEncoder(containerFormat);

                if (decoder.Metadata != null)
                {
                    try
                    {
                        encoder.Metadata = decoder.Metadata;
                    }
                    catch (InvalidOperationException)
                    {
                    }
                }

                if (decoder.Palette != null)
                {
                    encoder.Palette = decoder.Palette;
                }

                foreach (var originalFrame in decoder.Frames)
                {
                    var transformedBitmap = Transform(originalFrame);

                    // if the frame was not modified, we should not replace the metadata
                    if (transformedBitmap == originalFrame)
                    {
                        encoder.Frames.Add(originalFrame);
                    }
                    else
                    {
                        BitmapMetadata originalMetadata = (BitmapMetadata)originalFrame.Metadata;

    #if DEBUG
                        Debug.WriteLine($"### Processing metadata of file {_file}");
                        originalMetadata.PrintsAllMetadataToDebugOutput();
    #endif

                        var metadata = GetValidMetadata(originalMetadata, transformedBitmap, containerFormat);

                        if (_settings.RemoveMetadata && metadata != null)
                        {
                            // strip any metadata that doesn't affect rendering
                            var newMetadata = new BitmapMetadata(metadata.Format);

                            metadata.CopyMetadataPropertyTo(newMetadata, "System.Photo.Orientation");
                            metadata.CopyMetadataPropertyTo(newMetadata, "System.Image.ColorSpace");

                            metadata = newMetadata;
                        }

                        var frame = CreateBitmapFrame(transformedBitmap, metadata);

                        encoder.Frames.Add(frame);
                    }
                }

                path = GetDestinationPath(encoder);
                _fileSystem.Directory.CreateDirectory(_fileSystem.Path.GetDirectoryName(path));
                using (var outputStream = _fileSystem.File.Open(path, FileMode.CreateNew, FileAccess.Write))
                {
                    encoder.Save(outputStream);
                }
            }

            if (_settings.KeepDateModified)
            {
                _fileSystem.File.SetLastWriteTimeUtc(path, _fileSystem.File.GetLastWriteTimeUtc(_file));
            }

            if (_settings.Replace)
            {
                var backup = GetBackupPath();
                _fileSystem.File.Replace(path, _file, backup, ignoreMetadataErrors: true);
                FileSystem.DeleteFile(backup, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin);
            }
        }
コード例 #16
0
ファイル: ResizeOperation.cs プロジェクト: rdeveen/PowerToys
        public void Execute()
        {
            string path;

            using (var inputStream = _fileSystem.File.OpenRead(_file))
            {
                var decoder = BitmapDecoder.Create(
                    inputStream,
                    BitmapCreateOptions.PreservePixelFormat,
                    BitmapCacheOption.None);

                var encoder = BitmapEncoder.Create(decoder.CodecInfo.ContainerFormat);
                if (!encoder.CanEncode())
                {
                    encoder = BitmapEncoder.Create(_settings.FallbackEncoder);
                }

                ConfigureEncoder(encoder);

                if (decoder.Metadata != null)
                {
                    try
                    {
                        encoder.Metadata = decoder.Metadata;
                    }
                    catch (InvalidOperationException)
                    {
                    }
                }

                if (decoder.Palette != null)
                {
                    encoder.Palette = decoder.Palette;
                }

                foreach (var originalFrame in decoder.Frames)
                {
                    BitmapMetadata metadata = (BitmapMetadata)originalFrame.Metadata;
                    if (metadata != null)
                    {
                        try
                        {
#if DEBUG
                            Debug.WriteLine($"### Processing metadata of file {_file}");
                            metadata.PrintsAllMetadataToDebugOutput();
#endif

                            // read all metadata and build up metadata object from the scratch. Discard invalid (unreadable/unwritable) metadata.
                            var newMetadata    = new BitmapMetadata(metadata.Format);
                            var listOfMetadata = metadata.GetListOfMetadata();
                            foreach (var(metadataPath, value) in listOfMetadata)
                            {
                                if (value is BitmapMetadata bitmapMetadata)
                                {
                                    var innerMetadata = new BitmapMetadata(bitmapMetadata.Format);
                                    newMetadata.SetQuerySafe(metadataPath, innerMetadata);
                                }
                                else
                                {
                                    newMetadata.SetQuerySafe(metadataPath, value);
                                }
                            }

                            if (newMetadata.IsMetadataObjectValid())
                            {
                                metadata = newMetadata;
                            }
                            else
                            {
                                // Seems like we build an invalid metadata object. ImageResizer will fail when trying to write the image to disk. We discard all metadata to be able to save the image.
                                metadata = null;
                            }
                        }
                        catch (ArgumentException ex)
                        {
                            metadata = null;

                            Debug.WriteLine(ex);
                        }
                    }

                    if (_settings.RemoveMetadata && metadata != null)
                    {
                        // strip any metadata that doesn't affect rendering
                        var newMetadata = new BitmapMetadata(metadata.Format);

                        metadata.CopyMetadataPropertyTo(newMetadata, "System.Photo.Orientation");
                        metadata.CopyMetadataPropertyTo(newMetadata, "System.Image.ColorSpace");

                        metadata = newMetadata;
                    }

                    encoder.Frames.Add(
                        BitmapFrame.Create(
                            Transform(originalFrame),
                            thumbnail: null, /* should be null, see #15413 */
                            metadata,
                            colorContexts: null /* should be null, see #14866 */));
                }

                path = GetDestinationPath(encoder);
                _fileSystem.Directory.CreateDirectory(_fileSystem.Path.GetDirectoryName(path));
                using (var outputStream = _fileSystem.File.Open(path, FileMode.CreateNew, FileAccess.Write))
                {
                    encoder.Save(outputStream);
                }
            }

            if (_settings.KeepDateModified)
            {
                _fileSystem.File.SetLastWriteTimeUtc(path, _fileSystem.File.GetLastWriteTimeUtc(_file));
            }

            if (_settings.Replace)
            {
                var backup = GetBackupPath();
                _fileSystem.File.Replace(path, _file, backup, ignoreMetadataErrors: true);
                FileSystem.DeleteFile(backup, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin);
            }
        }
コード例 #17
0
        public void Execute()
        {
            string path;

            using (var inputStream = _fileSystem.File.OpenRead(_file))
            {
                var decoder = BitmapDecoder.Create(
                    inputStream,
                    BitmapCreateOptions.PreservePixelFormat,
                    BitmapCacheOption.None);

                var encoder = BitmapEncoder.Create(decoder.CodecInfo.ContainerFormat);
                if (!encoder.CanEncode())
                {
                    encoder = BitmapEncoder.Create(_settings.FallbackEncoder);
                }

                ConfigureEncoder(encoder);

                if (decoder.Metadata != null)
                {
                    try
                    {
                        encoder.Metadata = decoder.Metadata;
                    }
                    catch (InvalidOperationException)
                    {
                    }
                }

                if (decoder.Palette != null)
                {
                    encoder.Palette = decoder.Palette;
                }

                foreach (var originalFrame in decoder.Frames)
                {
                    BitmapMetadata metadata = (BitmapMetadata)originalFrame.Metadata;
                    if (metadata != null)
                    {
                        try
                        {
                            // Detect whether metadata can copied successfully
                            _ = metadata.Clone();
                        }
                        catch (ArgumentException)
                        {
                            metadata = null;
                        }
                    }

                    if (_settings.RemoveMetadata && metadata != null)
                    {
                        // strip any metadata that doesn't affect rendering
                        var newMetadata = new BitmapMetadata(metadata.Format);

                        metadata.CopyMetadataPropertyTo(newMetadata, "System.Photo.Orientation");
                        metadata.CopyMetadataPropertyTo(newMetadata, "System.Image.ColorSpace");

                        metadata = newMetadata;
                    }

                    encoder.Frames.Add(
                        BitmapFrame.Create(
                            Transform(originalFrame),
                            thumbnail: null,
                            metadata,
                            colorContexts: null));
                }

                path = GetDestinationPath(encoder);
                _fileSystem.Directory.CreateDirectory(_fileSystem.Path.GetDirectoryName(path));
                using (var outputStream = _fileSystem.File.Open(path, FileMode.CreateNew, FileAccess.Write))
                {
                    encoder.Save(outputStream);
                }
            }

            if (_settings.KeepDateModified)
            {
                _fileSystem.File.SetLastWriteTimeUtc(path, _fileSystem.File.GetLastWriteTimeUtc(_file));
            }

            if (_settings.Replace)
            {
                var backup = GetBackupPath();
                _fileSystem.File.Replace(path, _file, backup, ignoreMetadataErrors: true);
                FileSystem.DeleteFile(backup, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin);
            }
        }
コード例 #18
0
ファイル: BenRunner-old.cs プロジェクト: lulzzz/openMIC
        private void BuildBenLinkDLINI(List <BenRecord> fileList)
        {
            string requestfilename = localPath + "\\benlink.req";

            string myINIFile = "[Signature]" + System.Environment.NewLine +
                               "Program=BenLink" + System.Environment.NewLine +
                               "FileType=Request" + System.Environment.NewLine +
                               "FileVersion=1" + System.Environment.NewLine +
                               System.Environment.NewLine +
                               "[General]" + System.Environment.NewLine +
                               "NbRequest=" + fileList.Count.ToString() + System.Environment.NewLine +
                               System.Environment.NewLine +
                               "[Device]" + System.Environment.NewLine +
                               "DeviceType=5" + System.Environment.NewLine +
                               "DeviceSN=" + serialNumber + System.Environment.NewLine +
                               "NominalFrequency=60" + System.Environment.NewLine +
                               "DataDirectory=" + localPath + '\\' + System.Environment.NewLine +
                               System.Environment.NewLine +
                               "CommAddress=1" + System.Environment.NewLine +
                               "[ConnectionParam]" + System.Environment.NewLine +
                               "AccessType=0" + System.Environment.NewLine +
                               "UserName=0" + System.Environment.NewLine +
                               "IPAddress=" + ipAddress + System.Environment.NewLine +
                               "HangupTimeout=0";

            int i       = 1;
            int curYear = DateTime.Now.Year;

            foreach (BenRecord currec in fileList)
            {
                if (currec.rDateTime.Year > curYear)
                {
                    SendFileFromFutureNotification("Record ID: " + currec.rId);
                    throw new System.Exception("FileID " + currec.rId + " at site " + siteName + " from the future. Fix DFR clock.");
                }

                if (currec.rDateTime > System.IO.File.GetLastWriteTime(lastFileDownloaded))
                {
                    //Program.Log("Compare: " + currec.rId + ' ' + currec.rDateTime.ToString() + " > " + System.IO.File.GetLastWriteTime(lastFileDownloaded));
                    myINIFile += System.Environment.NewLine + System.Environment.NewLine + System.Environment.NewLine + "[Request" + i++ + "]" + System.Environment.NewLine +
                                 "RequestType=2" + System.Environment.NewLine +
                                 "RecordNum=" + currec.rId + System.Environment.NewLine +
                                 "SubBenNum=0" + System.Environment.NewLine +
                                 "Origin=1" + System.Environment.NewLine +
                                 "OptionFlags=1" + System.Environment.NewLine +
                                 "DataPath=" + localPath + System.Environment.NewLine +
                                 "FileName=" + get232FN(currec.rDateTime, serialNumber);
                }
                //"FileName=" +currec.rDateTime.ToString("yyMMdd,HHmmssfff") +"," +tzoffset +"," +Replace(sitename, " ", "_") +"," +siteuser +",TVA"
                //working "FileName=" +siteuser +"-" +currec.rId +"-" +currec.rDateTime.ToString("yyMMdd-HHmmssfff")
                //using the property in the site base class for bens.
                //if it causes problems with the openFLE we may need to 2 folders one for the aux files and one for the
                //comtrade data itself.  may want to consider making this a property in the app.config file.
                //"DataPath=" +Replace(localPath, "E:\ben", "E:\bencomtrade") +System.Environment.NewLine +_
            }


            try
            {
                System.IO.FileInfo file = new System.IO.FileInfo(requestfilename);
                file.Directory.Create();
                FileSystem.WriteAllText(file.FullName, myINIFile, false, System.Text.Encoding.ASCII);
            }
            catch (Exception ex)
            {
                Program.Log("BuildBenLinkDLINI error: " + siteName + " - " + ex.ToString());

                throw new System.Exception("BuildBenLinkDLINI error: " + siteName + " - " + ex.ToString());
            }
        }