本文整理汇总了C#中Nikse.SubtitleEdit.Logic.Subtitle.ToText方法的典型用法代码示例。如果您正苦于以下问题:C# Subtitle.ToText方法的具体用法?C# Subtitle.ToText怎么用?C# Subtitle.ToText使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Nikse.SubtitleEdit.Logic.Subtitle
的用法示例。
在下文中一共展示了Subtitle.ToText方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: BatchConvertSave
internal static bool BatchConvertSave(string toFormat, string offset, Encoding targetEncoding, string outputFolder, int count, ref int converted, ref int errors, IList<SubtitleFormat> formats, string fileName, Subtitle sub, SubtitleFormat format, bool overwrite, string pacCodePage)
{
// adjust offset
if (!string.IsNullOrEmpty(offset) && (offset.StartsWith("/offset:") || offset.StartsWith("offset:")))
{
string[] parts = offset.Split(":".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
if (parts.Length == 5)
{
try
{
TimeSpan ts = new TimeSpan(0, int.Parse(parts[1].TrimStart('-')), int.Parse(parts[2]), int.Parse(parts[3]), int.Parse(parts[4]));
if (parts[1].StartsWith("-"))
sub.AddTimeToAllParagraphs(ts.Negate());
else
sub.AddTimeToAllParagraphs(ts);
}
catch
{
Console.Write(" (unable to read offset " + offset + ")");
}
}
}
bool targetFormatFound = false;
string outputFileName;
foreach (SubtitleFormat sf in formats)
{
if (sf.Name.ToLower().Replace(" ", string.Empty) == toFormat.ToLower() || sf.Name.ToLower().Replace(" ", string.Empty) == toFormat.Replace(" ", string.Empty).ToLower())
{
targetFormatFound = true;
sf.BatchMode = true;
outputFileName = FormatOutputFileNameForBatchConvert(fileName, sf.Extension, outputFolder, overwrite);
Console.Write(string.Format("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName));
if (sf.IsFrameBased && !sub.WasLoadedWithFrameNumbers)
sub.CalculateFrameNumbersFromTimeCodesNoCheck(Configuration.Settings.General.CurrentFrameRate);
else if (sf.IsTimeBased && sub.WasLoadedWithFrameNumbers)
sub.CalculateTimeCodesFromFrameNumbers(Configuration.Settings.General.CurrentFrameRate);
File.WriteAllText(outputFileName, sub.ToText(sf), targetEncoding);
if (format.GetType() == typeof(Sami) || format.GetType() == typeof(SamiModern))
{
var sami = (Sami)format;
foreach (string className in Sami.GetStylesFromHeader(sub.Header))
{
var newSub = new Subtitle();
foreach (Paragraph p in sub.Paragraphs)
{
if (p.Extra != null && p.Extra.ToLower().Trim() == className.ToLower().Trim())
newSub.Paragraphs.Add(p);
}
if (newSub.Paragraphs.Count > 0 && newSub.Paragraphs.Count < sub.Paragraphs.Count)
{
string s = fileName;
if (s.LastIndexOf('.') > 0)
s = s.Insert(s.LastIndexOf('.'), "_" + className);
else
s += "_" + className + format.Extension;
outputFileName = FormatOutputFileNameForBatchConvert(s, sf.Extension, outputFolder, overwrite);
File.WriteAllText(outputFileName, newSub.ToText(sf), targetEncoding);
}
}
}
Console.WriteLine(" done.");
}
}
if (!targetFormatFound)
{
var ebu = new Ebu();
if (ebu.Name.ToLower().Replace(" ", string.Empty) == toFormat.ToLower())
{
targetFormatFound = true;
outputFileName = FormatOutputFileNameForBatchConvert(fileName, ebu.Extension, outputFolder, overwrite);
Console.Write(string.Format("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName));
ebu.Save(outputFileName, sub);
Console.WriteLine(" done.");
}
}
if (!targetFormatFound)
{
var pac = new Pac();
if (pac.Name.ToLower().Replace(" ", string.Empty) == toFormat.ToLower() || toFormat.ToLower() == "pac" || toFormat.ToLower() == ".pac")
{
pac.BatchMode = true;
if (!string.IsNullOrEmpty(pacCodePage) && Utilities.IsInteger(pacCodePage))
pac.CodePage = Convert.ToInt32(pacCodePage);
targetFormatFound = true;
outputFileName = FormatOutputFileNameForBatchConvert(fileName, pac.Extension, outputFolder, overwrite);
Console.Write(string.Format("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName));
pac.Save(outputFileName, sub);
Console.WriteLine(" done.");
}
}
if (!targetFormatFound)
{
var cavena890 = new Cavena890();
if (cavena890.Name.ToLower().Replace(" ", string.Empty) == toFormat.ToLower())
{
targetFormatFound = true;
outputFileName = FormatOutputFileNameForBatchConvert(fileName, cavena890.Extension, outputFolder, overwrite);
Console.Write(string.Format("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName));
cavena890.Save(outputFileName, sub);
//.........这里部分代码省略.........
示例2: SavePart
private void SavePart(Subtitle part, string title, string name)
{
saveFileDialog1.Title = title;
saveFileDialog1.FileName = name;
Utilities.SetSaveDialogFilter(saveFileDialog1, _format);
saveFileDialog1.DefaultExt = "*" + _format.Extension;
saveFileDialog1.AddExtension = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string fileName = saveFileDialog1.FileName;
try
{
if (File.Exists(fileName))
File.Delete(fileName);
int index = 0;
foreach (SubtitleFormat format in SubtitleFormat.AllSubtitleFormats)
{
if (saveFileDialog1.FilterIndex == index + 1)
File.WriteAllText(fileName, part.ToText(format), _encoding);
index++;
}
}
catch
{
MessageBox.Show(string.Format(Configuration.Settings.Language.SplitSubtitle.UnableToSaveFileX, fileName));
}
}
}
示例3: ToolStripMenuItemSaveSelectedLinesClick
private void ToolStripMenuItemSaveSelectedLinesClick(object sender, EventArgs e)
{
var newSub = new Subtitle(_subtitle);
newSub.Header = _subtitle.Header;
newSub.Paragraphs.Clear();
foreach (int index in SubtitleListview1.SelectedIndices)
newSub.Paragraphs.Add(_subtitle.Paragraphs[index]);
SubtitleFormat currentFormat = GetCurrentSubtitleFormat();
Utilities.SetSaveDialogFilter(saveFileDialog1, currentFormat);
saveFileDialog1.Title = _language.SaveSubtitleAs;
saveFileDialog1.DefaultExt = "*" + currentFormat.Extension;
saveFileDialog1.AddExtension = true;
if (!string.IsNullOrEmpty(_fileName))
saveFileDialog1.InitialDirectory = Path.GetDirectoryName(_fileName);
if (saveFileDialog1.ShowDialog(this) == DialogResult.OK)
{
int index = 0;
foreach (SubtitleFormat format in SubtitleFormat.AllSubtitleFormats)
{
if (saveFileDialog1.FilterIndex == index + 1)
{
// only allow current extension or ".txt"
string fileName = saveFileDialog1.FileName;
string ext = Path.GetExtension(fileName).ToLower();
bool extOk = ext == format.Extension.ToLower() || format.AlternateExtensions.Contains(ext) || ext == ".txt";
if (!extOk)
{
if (fileName.EndsWith("."))
fileName = fileName.Substring(0, _fileName.Length - 1);
fileName += format.Extension;
}
string allText = newSub.ToText(format);
File.WriteAllText(fileName, allText, GetCurrentEncoding());
ShowStatus(string.Format(_language.XLinesSavedAsY, newSub.Paragraphs.Count, fileName));
return;
}
index++;
}
}
}
示例4: SaveSubtitle
private DialogResult SaveSubtitle(SubtitleFormat format)
{
if (string.IsNullOrEmpty(_fileName) || _converted)
return FileSaveAs(false);
try
{
string allText = _subtitle.ToText(format);
// Seungki begin
if (_splitDualSami && _subtitleAlternate != null)
{
var s = new Subtitle(_subtitle);
foreach (Paragraph p in _subtitleAlternate.Paragraphs)
s.Paragraphs.Add(p);
allText = s.ToText(format);
}
// Seungki end
var currentEncoding = GetCurrentEncoding();
if (currentEncoding == Encoding.Default && (allText.Contains("♪") || allText.Contains("♫") || allText.Contains("♥") || allText.Contains("—") || allText.Contains("…"))) // ANSI & music/unicode symbols
{
if (MessageBox.Show(string.Format(_language.UnicodeMusicSymbolsAnsiWarning), Title, MessageBoxButtons.YesNo) == DialogResult.No)
return DialogResult.No;
}
bool containsNegativeTime = false;
foreach (var p in _subtitle.Paragraphs)
{
if (p.StartTime.TotalMilliseconds < 0 || p.EndTime.TotalMilliseconds < 0)
{
containsNegativeTime = true;
break;
}
}
if (containsNegativeTime && !string.IsNullOrEmpty(_language.NegativeTimeWarning))
{
if (MessageBox.Show(_language.NegativeTimeWarning, Title, MessageBoxButtons.YesNo) == DialogResult.No)
return DialogResult.No;
}
if (File.Exists(_fileName))
{
DateTime fileOnDisk = File.GetLastWriteTime(_fileName);
if (_fileDateTime != fileOnDisk && _fileDateTime != new DateTime())
{
if (MessageBox.Show(string.Format(_language.OverwriteModifiedFile,
_fileName, fileOnDisk.ToShortDateString(), fileOnDisk.ToString("HH:mm:ss"),
Environment.NewLine, _fileDateTime.ToShortDateString(), _fileDateTime.ToString("HH:mm:ss")),
Title + " - " + _language.FileOnDiskModified, MessageBoxButtons.YesNo) == DialogResult.No)
return DialogResult.No;
}
File.Delete(_fileName);
}
if (Control.ModifierKeys == (Keys.Control | Keys.Shift))
allText = allText.Replace("\r\n", "\n");
if (format.GetType() == typeof(ItunesTimedText))
{
Encoding outputEnc = new UTF8Encoding(false); // create encoding with no BOM
TextWriter file = new StreamWriter(_fileName, false, outputEnc); // open file with encoding
file.Write(allText);
file.Close(); // save and close it
}
else if (currentEncoding == Encoding.UTF8 && (format.GetType() == typeof(TmpegEncAW5) || format.GetType() == typeof(TmpegEncXml)))
{
Encoding outputEnc = new UTF8Encoding(false); // create encoding with no BOM
TextWriter file = new StreamWriter(_fileName, false, outputEnc); // open file with encoding
file.Write(allText);
file.Close(); // save and close it
}
else
{
if (allText.Trim().Length == 0)
{
MessageBox.Show(string.Format(_language.UnableToSaveSubtitleX, _fileName) + Environment.NewLine + Environment.NewLine + "Subtitle seems to be empty - try to re-save if you're working on a valid subtitle!");
return DialogResult.Cancel;
}
File.WriteAllText(_fileName, allText, currentEncoding);
}
_fileDateTime = File.GetLastWriteTime(_fileName);
ShowStatus(string.Format(_language.SavedSubtitleX, _fileName));
_changeSubtitleToString = SerializeSubtitle(_subtitle);
return DialogResult.OK;
}
catch (Exception exception)
{
MessageBox.Show(string.Format(_language.UnableToSaveSubtitleX, _fileName));
System.Diagnostics.Debug.Write(exception.Message);
return DialogResult.Cancel;
}
}
示例5: joinSessionToolStripMenuItem_Click
private void joinSessionToolStripMenuItem_Click(object sender, EventArgs e)
{
_networkSession = new NikseWebServiceSession(_subtitle, _subtitleAlternate, TimerWebServiceTick, OnUpdateUserLogEntries);
NetworkJoin networkJoin = new NetworkJoin();
networkJoin.Initialize(_networkSession);
if (networkJoin.ShowDialog(this) == DialogResult.OK)
{
_subtitle = _networkSession.Subtitle;
_subtitleAlternate = _networkSession.OriginalSubtitle;
if (_subtitleAlternate != null && _subtitleAlternate.Paragraphs.Count > 0)
SubtitleListview1.ShowAlternateTextColumn(Configuration.Settings.Language.General.OriginalText);
_fileName = networkJoin.FileName;
SetTitle();
Text = Title;
toolStripStatusNetworking.Visible = true;
toolStripStatusNetworking.Text = _language.NetworkMode;
EnableDisableControlsNotWorkingInNetworkMode(false);
_networkSession.AppendToLog(string.Format(_language.XStartedSessionYAtZ, _networkSession.CurrentUser.UserName, _networkSession.SessionId, DateTime.Now.ToLongTimeString()));
SubtitleListview1.ShowExtraColumn(_language.UserAndAction);
SubtitleListview1.AutoSizeAllColumns(this);
_subtitleListViewIndex = -1;
_oldSelectedParagraph = null;
if (Configuration.Settings.General.AllowEditOfOriginalSubtitle && _subtitleAlternate != null && _subtitleAlternate.Paragraphs.Count > 0)
{
buttonUnBreak.Visible = false;
buttonAutoBreak.Visible = false;
buttonSplitLine.Visible = false;
textBoxListViewText.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Bottom;
textBoxListViewText.Width = (groupBoxEdit.Width - (textBoxListViewText.Left + 10)) / 2;
textBoxListViewTextAlternate.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Bottom;
textBoxListViewTextAlternate.Left = textBoxListViewText.Left + textBoxListViewText.Width + 3;
textBoxListViewTextAlternate.Width = textBoxListViewText.Width;
textBoxListViewTextAlternate.Visible = true;
labelAlternateText.Text = Configuration.Settings.Language.General.OriginalText;
labelAlternateText.Visible = true;
labelAlternateCharactersPerSecond.Visible = true;
labelTextAlternateLineLengths.Visible = true;
labelAlternateSingleLine.Visible = true;
labelTextAlternateLineTotal.Visible = true;
labelCharactersPerSecond.Left = textBoxListViewText.Left + (textBoxListViewText.Width - labelCharactersPerSecond.Width);
labelTextLineTotal.Left = textBoxListViewText.Left + (textBoxListViewText.Width - labelTextLineTotal.Width);
AddAlternate();
Main_Resize(null, null);
_changeAlternateSubtitleToString = _subtitleAlternate.ToText(new SubRip()).Trim();
}
else
{
RemoveAlternate(false);
}
SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
SubtitleListview1.SelectIndexAndEnsureVisible(0);
TimerWebServiceTick(null, null);
}
else
{
_networkSession = null;
}
}
示例6: ToolStripMenuItemCopySourceTextClick
private void ToolStripMenuItemCopySourceTextClick(object sender, EventArgs e)
{
Subtitle selectedLines = new Subtitle(_subtitle);
selectedLines.Paragraphs.Clear();
foreach (int index in SubtitleListview1.SelectedIndices)
selectedLines.Paragraphs.Add(_subtitle.Paragraphs[index]);
Clipboard.SetText(selectedLines.ToText(GetCurrentSubtitleFormat()));
}
示例7: SubtitleListview1KeyDown
private void SubtitleListview1KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.C && e.Modifiers == Keys.Control) //Ctrl+c = Copy to clipboard
{
var tmp = new Subtitle();
foreach (int i in SubtitleListview1.SelectedIndices)
{
Paragraph p = _subtitle.GetParagraphOrDefault(i);
if (p != null)
tmp.Paragraphs.Add(new Paragraph(p));
}
if (tmp.Paragraphs.Count > 0)
{
Clipboard.SetText(tmp.ToText(new SubRip()));
}
e.SuppressKeyPress = true;
}
else if (e.KeyData == _mainListViewCopyText)
{
StringBuilder sb = new StringBuilder();
foreach (int i in SubtitleListview1.SelectedIndices)
{
Paragraph p = _subtitle.GetParagraphOrDefault(i);
if (p != null)
sb.AppendLine(p.Text + Environment.NewLine);
}
if (sb.Length > 0)
{
Clipboard.SetText(sb.ToString().Trim());
}
e.SuppressKeyPress = true;
}
else if (e.KeyData == _mainListViewAutoDuration)
{
MakeAutoDurationSelectedLines();
}
else if (e.KeyData == _mainListViewFocusWaveform)
{
if (audioVisualizer.CanFocus)
{
audioVisualizer.Focus();
e.SuppressKeyPress = true;
}
}
else if (e.KeyCode == Keys.V && e.Modifiers == Keys.Control) //Ctrl+vPaste from clipboard
{
if (Clipboard.ContainsText())
{
string text = Clipboard.GetText();
var tmp = new Subtitle();
var format = new SubRip();
var list = new List<string>();
foreach (string line in text.Replace(Environment.NewLine, "|").Split("|".ToCharArray(), StringSplitOptions.None))
list.Add(line);
format.LoadSubtitle(tmp, list, null);
if (SubtitleListview1.SelectedItems.Count == 1 && tmp.Paragraphs.Count > 0)
{
MakeHistoryForUndo(_language.BeforeInsertLine);
_makeHistoryPaused = true;
Paragraph lastParagraph = null;
Paragraph lastTempParagraph = null;
foreach (Paragraph p in tmp.Paragraphs)
{
InsertAfter();
textBoxListViewText.Text = p.Text;
if (lastParagraph != null && lastTempParagraph != null)
{
double millisecondsBetween = p.StartTime.TotalMilliseconds - lastTempParagraph.EndTime.TotalMilliseconds;
timeUpDownStartTime.TimeCode = new TimeCode(TimeSpan.FromMilliseconds(lastParagraph.EndTime.TotalMilliseconds + millisecondsBetween));
}
SetDurationInSeconds(p.Duration.TotalSeconds);
lastParagraph = _subtitle.GetParagraphOrDefault(_subtitleListViewIndex);
lastTempParagraph = p;
}
RestartHistory();
}
else if (SubtitleListview1.Items.Count == 0 && tmp.Paragraphs.Count > 0)
{ // insert into empty subtitle
MakeHistoryForUndo(_language.BeforeInsertLine);
foreach (Paragraph p in tmp.Paragraphs)
{
_subtitle.Paragraphs.Add(p);
}
SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
SubtitleListview1.SelectIndexAndEnsureVisible(0, true);
}
else if (list.Count > 1 && list.Count < 2000)
{
MakeHistoryForUndo(_language.BeforeInsertLine);
_makeHistoryPaused = true;
foreach (string line in list)
{
if (line.Trim().Length > 0)
{
InsertAfter();
textBoxListViewText.Text = Utilities.AutoBreakLine(line);
}
}
RestartHistory();
}
//.........这里部分代码省略.........
示例8: SubStationAlphaProperties
public SubStationAlphaProperties(Subtitle subtitle, SubtitleFormat format, string videoFileName, string subtitleFileName)
{
InitializeComponent();
_subtitle = subtitle;
_isSubStationAlpha = format.FriendlyName == new SubStationAlpha().FriendlyName;
_videoFileName = videoFileName;
var l = Configuration.Settings.Language.SubStationAlphaProperties;
if (_isSubStationAlpha)
{
Text = l.TitleSubstationAlpha;
labelWrapStyle.Visible = false;
comboBoxWrapStyle.Visible = false;
checkBoxScaleBorderAndShadow.Visible = false;
Height = Height - (comboBoxWrapStyle.Height + checkBoxScaleBorderAndShadow.Height + 8);
}
else
{
Text = l.Title;
}
comboBoxWrapStyle.SelectedIndex = 2;
comboBoxCollision.SelectedIndex = 0;
string header = subtitle.Header;
if (subtitle.Header == null)
{
SubStationAlpha ssa = new SubStationAlpha();
var sub = new Subtitle();
var lines = new List<string>();
foreach (string line in subtitle.ToText(ssa).Replace(Environment.NewLine, "\n").Split('\n'))
lines.Add(line);
string title = "Untitled";
if (!string.IsNullOrEmpty(subtitleFileName))
title = Path.GetFileNameWithoutExtension(subtitleFileName);
else if (!string.IsNullOrEmpty(videoFileName))
title = Path.GetFileNameWithoutExtension(videoFileName);
ssa.LoadSubtitle(sub, lines, title);
header = sub.Header;
}
if (header != null)
{
foreach (string line in header.Split(Utilities.NewLineChars, StringSplitOptions.RemoveEmptyEntries))
{
string s = line.ToLower().Trim();
if (s.StartsWith("title:"))
{
textBoxTitle.Text = s.Remove(0, 6).Trim();
}
else if (s.StartsWith("original script:"))
{
textBoxOriginalScript.Text = s.Remove(0, 16).Trim();
}
else if (s.StartsWith("original translation:"))
{
textBoxTranslation.Text = s.Remove(0, 21).Trim();
}
else if (s.StartsWith("original editing:"))
{
textBoxEditing.Text = s.Remove(0, 17).Trim();
}
else if (s.StartsWith("original timing:"))
{
textBoxTiming.Text = s.Remove(0, 16).Trim();
}
else if (s.StartsWith("synch point:"))
{
textBoxSyncPoint.Text = s.Remove(0, 12).Trim();
}
else if (s.StartsWith("script updated by:"))
{
textBoxUpdatedBy.Text = s.Remove(0, 18).Trim();
}
else if (s.StartsWith("update details:"))
{
textBoxUpdateDetails.Text = s.Remove(0, 15).Trim();
}
else if (s.StartsWith("collisions:"))
{
if (s.Remove(0, 11).Trim() == "reverse")
comboBoxCollision.SelectedIndex = 1;
}
else if (s.StartsWith("playresx:"))
{
int number;
if (int.TryParse(s.Remove(0, 9).Trim(), out number))
numericUpDownVideoWidth.Value = number;
}
else if (s.StartsWith("playresy:"))
{
int number;
if (int.TryParse(s.Remove(0, 9).Trim(), out number))
numericUpDownVideoHeight.Value = number;
}
else if (s.StartsWith("scaledborderandshadow:"))
{
checkBoxScaleBorderAndShadow.Checked = s.Remove(0, 22).Trim().ToLower() == "yes";
}
}
//.........这里部分代码省略.........
示例9: SaveSubtitle
private DialogResult SaveSubtitle(SubtitleFormat format)
{
if (string.IsNullOrEmpty(_fileName) || _converted)
return FileSaveAs(false);
try
{
if (format != null && !format.IsTextBased)
{
if (format.GetType() == typeof(Ebu))
{
Ebu.Save(_fileName, _subtitle);
}
return DialogResult.OK;
}
string allText = _subtitle.ToText(format);
// Seungki begin
if (_splitDualSami && _subtitleAlternate != null)
{
var s = new Subtitle(_subtitle);
foreach (Paragraph p in _subtitleAlternate.Paragraphs)
s.Paragraphs.Add(p);
allText = s.ToText(format);
}
// Seungki end
var currentEncoding = GetCurrentEncoding();
bool isUnicode = currentEncoding == Encoding.Unicode || currentEncoding == Encoding.UTF32 || currentEncoding == Encoding.UTF7 || currentEncoding == Encoding.UTF8;
if (!isUnicode && (allText.Contains('♪') || allText.Contains('♫') || allText.Contains('♥') || allText.Contains('—') || allText.Contains('―') || allText.Contains('…'))) // ANSI & music/unicode symbols
{
if (MessageBox.Show(string.Format(_language.UnicodeMusicSymbolsAnsiWarning), Title, MessageBoxButtons.YesNo) == DialogResult.No)
return DialogResult.No;
}
if (!isUnicode)
{
allText = allText.Replace("—", "-"); // mdash, code 8212
allText = allText.Replace("―", "-"); // mdash, code 8213
allText = allText.Replace("…", "...");
allText = allText.Replace("♪", "#");
allText = allText.Replace("♫", "#");
}
bool containsNegativeTime = false;
foreach (var p in _subtitle.Paragraphs)
{
if (p.StartTime.TotalMilliseconds < 0 || p.EndTime.TotalMilliseconds < 0)
{
containsNegativeTime = true;
break;
}
}
if (containsNegativeTime && !string.IsNullOrEmpty(_language.NegativeTimeWarning))
{
if (MessageBox.Show(_language.NegativeTimeWarning, Title, MessageBoxButtons.YesNo) == DialogResult.No)
return DialogResult.No;
}
if (File.Exists(_fileName))
{
FileInfo fileInfo = new FileInfo(_fileName);
DateTime fileOnDisk = fileInfo.LastWriteTime;
if (_fileDateTime != fileOnDisk && _fileDateTime != new DateTime())
{
if (MessageBox.Show(string.Format(_language.OverwriteModifiedFile,
_fileName, fileOnDisk.ToShortDateString(), fileOnDisk.ToString("HH:mm:ss"),
Environment.NewLine, _fileDateTime.ToShortDateString(), _fileDateTime.ToString("HH:mm:ss")),
Title + " - " + _language.FileOnDiskModified, MessageBoxButtons.YesNo) == DialogResult.No)
return DialogResult.No;
}
if (fileInfo.IsReadOnly)
{
if (string.IsNullOrEmpty(_language.FileXIsReadOnly))
MessageBox.Show("Cannot save " + _fileName + Environment.NewLine + "File is read-only!");
else
MessageBox.Show(string.Format(_language.FileXIsReadOnly, _fileName));
return DialogResult.No;
}
}
if (Control.ModifierKeys == (Keys.Control | Keys.Shift))
allText = allText.Replace("\r\n", "\n");
if (format.GetType() == typeof(ItunesTimedText) || format.GetType() == typeof(ScenaristClosedCaptions) || format.GetType() == typeof(ScenaristClosedCaptionsDropFrame))
{
Encoding outputEnc = new UTF8Encoding(false); // create encoding with no BOM
TextWriter file = new StreamWriter(_fileName, false, outputEnc); // open file with encoding
file.Write(allText);
file.Close(); // save and close it
}
else if (currentEncoding == Encoding.UTF8 && (format.GetType() == typeof(TmpegEncAW5) || format.GetType() == typeof(TmpegEncXml)))
{
Encoding outputEnc = new UTF8Encoding(false); // create encoding with no BOM
TextWriter file = new StreamWriter(_fileName, false, outputEnc); // open file with encoding
file.Write(allText);
file.Close(); // save and close it
}
else
//.........这里部分代码省略.........
示例10: SavePart
/// <summary>
/// The save part.
/// </summary>
/// <param name="part">
/// The part.
/// </param>
/// <param name="title">
/// The title.
/// </param>
/// <param name="name">
/// The name.
/// </param>
private void SavePart(Subtitle part, string title, string name)
{
this.saveFileDialog1.Title = title;
this.saveFileDialog1.FileName = name;
Utilities.SetSaveDialogFilter(this.saveFileDialog1, this._format);
this.saveFileDialog1.DefaultExt = "*" + this._format.Extension;
this.saveFileDialog1.AddExtension = true;
if (this.saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string fileName = this.saveFileDialog1.FileName;
try
{
if (File.Exists(fileName))
{
File.Delete(fileName);
}
int index = 0;
foreach (SubtitleFormat format in SubtitleFormat.AllSubtitleFormats)
{
if (this.saveFileDialog1.FilterIndex == index + 1)
{
if (format.IsFrameBased)
{
part.CalculateFrameNumbersFromTimeCodesNoCheck(Configuration.Settings.General.CurrentFrameRate);
}
File.WriteAllText(fileName, part.ToText(format), this._encoding);
}
index++;
}
}
catch
{
MessageBox.Show(string.Format(Configuration.Settings.Language.SplitSubtitle.UnableToSaveFileX, fileName));
}
}
}
示例11: BatchConvertSave
internal static bool BatchConvertSave(string toFormat, string offset, Encoding targetEncoding, string outputFolder, int count, ref int converted, ref int errors, IList<SubtitleFormat> formats, string fileName, Subtitle sub, SubtitleFormat format, bool overwrite, string pacCodePage, double? targetFrameRate)
{
double oldFrameRate = Configuration.Settings.General.CurrentFrameRate;
try
{
// adjust offset
AdjustOffset(offset, sub);
// adjust frame rate
if (targetFrameRate.HasValue)
{
sub.ChangeFrameRate(Configuration.Settings.General.CurrentFrameRate, targetFrameRate.Value);
Configuration.Settings.General.CurrentFrameRate = targetFrameRate.Value;
}
bool targetFormatFound = false;
string outputFileName;
foreach (SubtitleFormat subtitleFormat in formats)
{
if (subtitleFormat.IsTextBased && (
subtitleFormat.Name.Replace(" ", string.Empty).Equals(toFormat, StringComparison.OrdinalIgnoreCase) ||
subtitleFormat.Name.Replace(" ", string.Empty).Equals(toFormat.Replace(" ", string.Empty), StringComparison.OrdinalIgnoreCase)))
{
targetFormatFound = true;
subtitleFormat.BatchMode = true;
outputFileName = FormatOutputFileNameForBatchConvert(fileName, subtitleFormat.Extension, outputFolder, overwrite);
Console.Write("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName);
if (subtitleFormat.IsFrameBased && !sub.WasLoadedWithFrameNumbers)
{
sub.CalculateFrameNumbersFromTimeCodesNoCheck(Configuration.Settings.General.CurrentFrameRate);
}
else if (subtitleFormat.IsTimeBased && sub.WasLoadedWithFrameNumbers)
{
sub.CalculateTimeCodesFromFrameNumbers(Configuration.Settings.General.CurrentFrameRate);
}
if ((subtitleFormat.GetType() == typeof(WebVTT) || subtitleFormat.GetType() == typeof(WebVTTFileWithLineNumber)))
{
targetEncoding = Encoding.UTF8;
}
if (subtitleFormat.GetType() == typeof(ItunesTimedText) || subtitleFormat.GetType() == typeof(ScenaristClosedCaptions) || subtitleFormat.GetType() == typeof(ScenaristClosedCaptionsDropFrame))
{
Encoding outputEnc = new UTF8Encoding(false);
using (var file = new StreamWriter(outputFileName, false, outputEnc))
{
file.Write(sub.ToText(subtitleFormat));
}
}
else if (targetEncoding == Encoding.UTF8 && (format.GetType() == typeof(TmpegEncAW5) || format.GetType() == typeof(TmpegEncXml)))
{
Encoding outputEnc = new UTF8Encoding(false);
using (var file = new StreamWriter(outputFileName, false, outputEnc))
{
file.Write(sub.ToText(subtitleFormat));
}
}
else
{
try
{
File.WriteAllText(outputFileName, sub.ToText(subtitleFormat), targetEncoding);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
errors++;
return false;
}
}
if (format.GetType() == typeof(Sami) || format.GetType() == typeof(SamiModern))
{
//var sami = (Sami)format;
foreach (string className in Sami.GetStylesFromHeader(sub.Header))
{
var newSub = new Subtitle();
foreach (Paragraph p in sub.Paragraphs)
{
if (p.Extra != null && p.Extra.Trim().Equals(className.Trim(), StringComparison.OrdinalIgnoreCase))
{
newSub.Paragraphs.Add(p);
}
}
if (newSub.Paragraphs.Count > 0 && newSub.Paragraphs.Count < sub.Paragraphs.Count)
{
string s = fileName;
if (s.LastIndexOf('.') > 0)
{
s = s.Insert(s.LastIndexOf('.'), "_" + className);
}
else
{
s += "_" + className + format.Extension;
}
outputFileName = FormatOutputFileNameForBatchConvert(s, subtitleFormat.Extension, outputFolder, overwrite);
//.........这里部分代码省略.........