本文整理汇总了C#中System.IO.FileInfo.MoveTo方法的典型用法代码示例。如果您正苦于以下问题:C# System.IO.FileInfo.MoveTo方法的具体用法?C# System.IO.FileInfo.MoveTo怎么用?C# System.IO.FileInfo.MoveTo使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.IO.FileInfo
的用法示例。
在下文中一共展示了System.IO.FileInfo.MoveTo方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Post
public async System.Threading.Tasks.Task<string> Post()
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = System.Web.HttpContext.Current.Server.MapPath("~/ImgUpload");
var provider = new MultipartFormDataStreamProvider(root);
try
{
System.Text.StringBuilder sb = new System.Text.StringBuilder(); // Holds the response body
// Read the form data and return an async task.
await Request.Content.ReadAsMultipartAsync(provider);
// This illustrates how to get the form data.
foreach (var key in provider.FormData.AllKeys)
{
foreach (var val in provider.FormData.GetValues(key))
{
sb.Append(string.Format("{0}: {1}\n", key, val));
}
}
var localfileURL = string.Empty;
var serverfileURL = string.Empty;
// This illustrates how to get the file names for uploaded files.
foreach (var file in provider.FileData)
{
System.IO.FileInfo fileInfo = new System.IO.FileInfo(file.LocalFileName);
sb.Append(string.Format("Uploaded file: {0} ({1} bytes)\n", fileInfo.Name, fileInfo.Length));
var fileName = Guid.NewGuid().ToString() + ".jpg";
localfileURL = System.Web.HttpContext.Current.Server.MapPath("~/ImgUpload/Img/" + fileName);
fileInfo.MoveTo(localfileURL);
//Fix URL
serverfileURL = new StringBuilder().Append("localhost").Append("/ImgUpload/Img/").Append(fileName).ToString();
}
return serverfileURL;
//return new HttpResponseMessage()
//{
// Content = new StringContent(sb.ToString())
//};
}
catch (System.Exception)
{
throw new HttpResponseException(HttpStatusCode.InternalServerError);
}
}
示例2: reName_OK_ClickEventHandler
private void reName_OK_ClickEventHandler(object sender, RoutedEventArgs e)
{
MessageBoxResult result;
string path = myViewModel.FileTreeVM.CurrentTreeItem.Path;
string existFileName;
System.IO.FileInfo file;
if (string.IsNullOrEmpty(change_FileName.Text))
{
result = MessageBox.Show("변경될 이름이 없습니다.", "오류");
return;
}
file = new System.IO.FileInfo(path);
existFileName = myViewModel.FileTreeVM.CurrentTreeItem.Name;
if (_isRename) path = path.Remove(path.Length - existFileName.Length);
else path += "\\";
path += change_FileName.Text;
if (_isRename && System.IO.File.Exists(path))
{
result = MessageBox.Show("같은 이름의 파일이 이미 존재합니다.", "오류");
return;
}
if (!_isRename && System.IO.Directory.Exists(path))
{
result = MessageBox.Show("같은 이름의 폴더가 이미 존재합니다.", "오류");
return;
}
if (_isRename)
{
file.MoveTo(path);
}
else
{
System.IO.Directory.CreateDirectory(path);
}
myViewModel.Update_ExplorerViewModel();
this.Close();
}
示例3: ErrorRenameXML
public static void ErrorRenameXML(System.Xml.XmlDocument doc, string sXMLFilename,
string sError, CarverLabUtility.Logger log, bool bDeleteOriginal)
{
log.WriteLog(sError);
System.IO.FileInfo fi = new System.IO.FileInfo(sXMLFilename);
fi.MoveTo(System.IO.Path.ChangeExtension(fi.FullName,".err"));
//System.IO.File.Move(sXMLFilename,sXMLFilename + ".err");
// log.WriteLog(" Renaming XML file...");
//if (doc == null)
//{
// doc = new System.Xml.XmlDocument();
// doc.Load(sXMLFilename);
//}
/*
System.Xml.XmlElement elt = doc.CreateElement("ENCODEERROR");
elt.InnerText = sError;
doc.DocumentElement.AppendChild(elt);
*/
//doc.Save(sXMLFilename + ".err");
//if (bDeleteOriginal)
// System.IO.File.Delete(sXMLFilename);
log.WriteLog(" XML file copied or renamed to: " + sXMLFilename + ".err");
}
示例4: SaveFile
private void SaveFile( string fileLocation, string rotateArguments, bool deleteOffDevice )
{
var fileName = Core.IO.Path.GetFileName ( fileLocation );
var sfd = new System.Windows.Forms.SaveFileDialog {
Title = "Copy Capture to PC",
DefaultExt = "mp4",
Filter = "Video (*.mp4)|*.mp4",
FilterIndex = 0,
ValidateNames = true,
FileName = fileName,
AddExtension = true,
OverwritePrompt = true,
};
this.InvokeIfRequired ( ( ) => {
if ( sfd.ShowDialog ( this ) == DialogResult.OK ) {
var finfo = DroidExplorer.Core.IO.FileInfo.Create ( System.IO.Path.GetFileName ( fileLocation ), 0, null,
null, null, DateTime.Now, false, fileLocation );
var tempFile = new System.IO.FileInfo ( System.IO.Path.Combine ( FolderManagement.TempFolder, "{0}.mp4".With ( System.IO.Path.GetFileNameWithoutExtension ( System.IO.Path.GetRandomFileName ( ) ) ) ) );
var dest = new System.IO.FileInfo ( sfd.FileName );
PluginHost.Pull ( finfo, tempFile );
if ( !string.IsNullOrWhiteSpace ( rotateArguments ) ) {
RotateVideo ( tempFile, dest, rotateArguments );
} else {
if ( dest.Exists ) {
dest.Delete ( );
}
tempFile.MoveTo ( dest.FullName );
}
if ( deleteOffDevice ) {
this.LogDebug ( "Deleting {0}", fileLocation );
PluginHost.CommandRunner.DeleteFile ( fileLocation );
}
}
} );
}
示例5: listViewFiles_AfterLabelEdit
private void listViewFiles_AfterLabelEdit(object sender, LabelEditEventArgs e)
{
if (e.Label == null)
return;
FileWithTags file = this.currentDatabase.Files[e.Item];
System.IO.FileInfo fileInfo = new System.IO.FileInfo(file.FileName);
string newFileName = file.FilePath + "\\" + e.Label;
try
{
if (newFileName.ToLower() != file.FileName.ToLower())
fileInfo.MoveTo(newFileName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
示例6: InitializeVirtualObjectListView
private void InitializeVirtualObjectListView()
{
this.virtualListViewFiles.RowGetter = delegate(int i)
{
FileWithTags file = this.currentDatabase.Files[i];
return file;
};
// Show the files
this.olvColumnFileName.AspectGetter = delegate(object x)
{
FileWithTags file = (FileWithTags)x;
return file.FileNameWithoutPath;
};
this.olvColumnFileName.AspectPutter = delegate(object x, object newValue)
{
FileWithTags file = (FileWithTags)x;
System.IO.FileInfo fileInfo = new System.IO.FileInfo(file.FileName);
string newFileName = file.FilePath + "\\" + newValue;
try
{
fileInfo.MoveTo(newFileName);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
};
// Draw the icon next to the name
this.olvColumnFileName.ImageGetter = delegate(object x)
{
FileWithTags file = (FileWithTags)x;
//CShItem
return this.iconExtractor.GetIndexByFileName(file.FileName);
};
// Show the tags
this.olvColumnTags.AspectGetter = delegate(object x)
{
FileWithTags file = (FileWithTags)x;
return file.Tags.ToString();
};
}
示例7: ImageButtonNext_Click
protected void ImageButtonNext_Click(object sender, ImageClickEventArgs e)
{
#warning 最大允许上传的文件尺寸
// DJUploadController1.Status.LengthExceeded
// The maximum upload size was exceeded
// Uploads were not processed via the module
if (!UploadManager.Instance.ModuleInstalled)
{
Warning.InnerHtml = "请配置文件上传的 Module";
return;
}
// Files uploaded
if (DJUploadController1.Status == null ||
DJUploadController1.Status.ErrorFiles.Count > 0 || // Files with errors
DJUploadController1.Status.UploadedFiles.Count != 1)
{
Warning.InnerHtml = "上传文件错误";
return;
}
// 获得文件名
UploadedFile videoUploadedFile = DJUploadController1.Status.UploadedFiles[0];
//// Exception
//if (f.Exception != null)
//{
// Warning.InnerHtml = string.Format("文件上传发生异常:{0}", f.Exception.Message);
// return;
//}
if (videoUploadedFile == null)
{
Warning.InnerHtml = "未正确获取上传的控件对象";
return;
}
#warning TODO:Uploads 作为配置项
string uploadsDirectory = "Uploads";
uploadsDirectory.Trim('/'); // 去除前后的 /
// 获得视频临时路径
string inFile = Server.MapPath(string.Format("/{0}/Temp/{1}", uploadsDirectory, System.IO.Path.GetFileName(videoUploadedFile.FileName)));
System.IO.FileInfo tempFileInfo = new System.IO.FileInfo(inFile);
if (!tempFileInfo.Exists)
{
Warning.InnerHtml = "上传文件错误,请重新上传";
return;
}
// 视频信息
Wis.Website.DataManager.VideoArticle videoArticle = null;
Wis.Website.DataManager.VideoArticleManager videoArticleManager = new Wis.Website.DataManager.VideoArticleManager();
int videoArticleCount = videoArticleManager.Count(this.ArticleGuid);
if (videoArticleCount == 0)
{
videoArticle = new Wis.Website.DataManager.VideoArticle();
videoArticle.VideoArticleGuid = Guid.NewGuid();
videoArticle.Article.ArticleGuid = article.ArticleGuid;
}
else
{
videoArticle = videoArticleManager.GetVideoArticle(this.ArticleGuid);
// 删除已存在的文件
if(System.IO.File.Exists(Page.MapPath(videoArticle.VideoPath)))
System.IO.File.Delete(Page.MapPath(videoArticle.VideoPath));
if(System.IO.File.Exists(Page.MapPath(videoArticle.FlvVideoPath)))
System.IO.File.Delete(Page.MapPath(videoArticle.FlvVideoPath));
if(System.IO.File.Exists(Page.MapPath(videoArticle.PreviewFramePath)))
System.IO.File.Delete(Page.MapPath(videoArticle.PreviewFramePath));
}
// 视频星级 Star
byte star;
if (byte.TryParse(RequestManager.Request("Star"), out star))
if (star != 0) videoArticle.Star = star;
// Videos 目录
string path = Server.MapPath(string.Format("/{0}/Videos/{1}/", uploadsDirectory, article.DateCreated.ToShortDateString()));
if (!System.IO.Directory.Exists(path)) System.IO.Directory.CreateDirectory(path);
// 视频,Flv视频,预览帧 路径
videoArticle.VideoPath = string.Format("/{0}/Videos/{1}/{2}{3}", uploadsDirectory, article.DateCreated.ToShortDateString(), this.ArticleGuid, tempFileInfo.Extension);
videoArticle.FlvVideoPath = Regex.Replace(videoArticle.VideoPath, tempFileInfo.Extension, ".swf", RegexOptions.IgnoreCase);
videoArticle.PreviewFramePath = Regex.Replace(videoArticle.VideoPath, tempFileInfo.Extension, ".jpg", RegexOptions.IgnoreCase);
// 3 创建缩微图 88x66
string ffmpegFile = Page.MapPath("Tools/ffmpeg.exe");
MediaHandler mediaHandler = new MediaHandler();
this.TotalSeconds = mediaHandler.GetTotalSeconds(ffmpegFile, inFile);
int timeOffset = (this.TotalSeconds % 2 == 0) ? (int)(this.TotalSeconds / 2) : ((int)(this.TotalSeconds / 2) + 1);
string outFile = Page.MapPath(videoArticle.PreviewFramePath);
mediaHandler.CreatePreviewFrame(ffmpegFile, timeOffset, inFile, outFile, this.ThumbnailWidth, this.ThumbnailHeight, new DataReceivedEventHandler(MediaHandler_DataReceived));
// 视频文件转移到 Videos 目录
tempFileInfo.MoveTo(Server.MapPath(videoArticle.VideoPath));
// 转换视频
if (tempFileInfo.Extension.ToLower() == ".flv" || tempFileInfo.Extension.ToLower() == ".swf")
{
//.........这里部分代码省略.........
示例8: Main
static void Main(string[] args)
{
ConfigurationClass oCfg = new ConfigurationClass();
IMSClasses.RabbitMQ.MessageQueue oRBFormatQueue = new MessageQueue(oCfg.RabbittMQ.Server, "", oCfg.RabbittMQ.ExcelQueueName);
/*IMSClasses.RabbitMQ.MessageQueue oRBExcelQueuePurge = new MessageQueue(oCfg.RabbittMQ.Server, "", oCfg.RabbittMQ.ExcelQueueName);
oRBExcelQueuePurge.purgeQueue();
oRBExcelQueuePurge.close();*/
//oRBQueue.purgeQueue();
//oRBQueue.addMessage(2);
while (true)
{
Console.WriteLine("Waiting for Jobs.............");
Int64 iTaskID = oRBFormatQueue.waitConsume();
bool bCorrect = true;
String sError = "";
System.Data.DataTable dt = null;
IMSClasses.DBHelper.db oDB = new IMSClasses.DBHelper.db(oCfg.ConnectionString);
System.Data.DataRow oRowTask = null;
try
{
oRowTask = oDB.getTask(iTaskID);
} catch(Exception eNotFound)
{
bCorrect = false;
}
if(bCorrect)
{
IMSClasses.Jobs.Task oCurrentTask = IMSClasses.Jobs.Task.getInstance(oRowTask["JSON"].ToString());
try
{
String sTemplatePath = System.IO.Path.Combine(oCfg.Paths.MainFolder, oCurrentTask.oJob.JOBCODE);
String sOutputPath = System.IO.Path.Combine(oCfg.Paths.MainFolder, oCurrentTask.oJob.JOBCODE);
sTemplatePath = System.IO.Path.Combine(sTemplatePath, oCfg.Paths.TemplateFolder);
sOutputPath = System.IO.Path.Combine(sOutputPath, oCfg.Paths.OutFolder);
oCurrentTask.oJob.InputParameters.SetupTemplatePaths(sTemplatePath);
oCurrentTask.oJob.OutputParameters.SetupPath(sOutputPath);
//String sJson = oCurrentJob.Serialize();
Console.WriteLine("Executiong of Format for job ID --> " + oCurrentTask.TaskID.ToString());
try
{
//dt = IMSClasses.excellHelpper.ExcelHelpper.getExcelData(oCurrentJob.InputParameters.Files[0].FileName, oCurrentJob.SQLParameters.TableName);
//ExcelHelpper.executeExcelTemplate(@"C:\Dev\IMS\bin\Templates\Top50Farmacias\Top50Farmacias\bin\Release\Top50Farmacias.xltx");
ExcelHelpper.executeExcelTemplate(oCurrentTask.oJob.InputParameters.TemplateFile.FileName);
}
catch (Exception xlException)
{
bCorrect = false;
sError = "Error formatting excel --> Exception --> " + xlException.Message;
}
oRBFormatQueue.markLastMessageAsProcessed();
//oRowTask = oDB.getTask(iTaskID);
oRowTask = oDB.getJob(oCurrentTask.oJob.JOBID);
IMSClasses.Jobs.Job oCurrentJob = IMSClasses.Jobs.Job.getInstance(oRowTask["JSON"].ToString());
if (!bCorrect || oCurrentJob.ReportStatus.Status.Equals("ERRO"))
{ //failure update
/*oCurrentJob.ReportStatus.ExecutionDate = DateTime.Now;
oCurrentJob.ReportStatus.Message = sError;
oCurrentJob.ReportStatus.Status = "ERRO";*/
Console.WriteLine(" <<Error>> " + sError);
oCurrentTask.UpdateDate = DateTime.Now;
oCurrentTask.TaskComments = oCurrentJob.ReportStatus.Message;
oCurrentTask.StatusFinal = oCurrentJob.ReportStatus.Status;
oCurrentTask.StatusCurrent = oCurrentJob.ReportStatus.Status;
}
else
{ //correct job update
/*como vamos por task y queremos manterlo estructurado en el servidor, vamos a mover el fichero generado*/
foreach (String sFile in System.IO.Directory.GetFiles(oCurrentJob.OutputParameters.DestinationFile.Directory))
{
System.IO.FileInfo oFileInfo = new System.IO.FileInfo(sFile);
String sNewPath = System.IO.Path.Combine(oCurrentJob.OutputParameters.DestinationFile.Directory, oCurrentTask.TaskID.ToString());
if (!System.IO.Directory.Exists(sNewPath)) System.IO.Directory.CreateDirectory(sNewPath);
oFileInfo.MoveTo(System.IO.Path.Combine(sNewPath, oFileInfo.Name));
}
oCurrentTask.oJob.ReportStatus.ExecutionDate = DateTime.Now;
oCurrentTask.oJob.ReportStatus.Message = "Format excel correctly";
oCurrentTask.oJob.ReportStatus.Status = "DONE";
oCurrentTask.UpdateDate = DateTime.Now;
oCurrentTask.TaskComments = "Format excel correctly";
oCurrentTask.StatusFinal = "DONE";
oCurrentTask.StatusCurrent = "DONE";
Console.WriteLine(" <<DONE>> " + oCurrentTask.StatusCurrent + " -- Date: " + oCurrentTask.UpdateDate.ToString());
}
oDB.updateJob(oCurrentTask.oJob.Serialize(), oCurrentTask.oJob.JOBID);
oDB.updateTask(oCurrentTask);
//.........这里部分代码省略.........
示例9: processChecker_Tick
private void processChecker_Tick(object sender, EventArgs e)
{
System.Diagnostics.Process[] process = System.Diagnostics.Process.GetProcesses();
bool doIt = true;
string fn = "";
string em = "";
string newName = "";
bool moveFile = true;
int howFar = 0;
System.IntPtr handle = (System.IntPtr)FindWindowEx(0, 0, "#32770", "PS Monitor");
if (handle == psWindow)
handle = (System.IntPtr)FindWindowEx((int)psWindow, 0, "#32770", "PS Monitor");
if ((GetWindowLongA(handle, GWL_STYLE) & TARGETWINDOW) == TARGETWINDOW)
{
SendMessage((int)handle, WM_COMMAND, WM_CLOSE, 0);
hpPrintCounter++;
if(showPrintMessages.Checked)
notifyIcon1.ShowBalloon("HP Lab Printer Count", hpPrintCounter.ToString() + " prints handled by PS Monitor. Annoying notification has been disabled via CCM.", CCMClient.NotifyIconEx.NotifyInfoFlags.Info, 15000);
if (handle != null)
if ((int)handle > 0)
psWindow = handle;
}
for (int i = 0; i < process.Length && doIt; i++)
{
if (!lastProcessList.Contains(process[i].Id) && !menuItem11.Checked)
try
{
howFar = 1;
//howFar = process[i].Id;
try
{
fn = process[i].MainModule.FileName.ToLower();
}
catch (Exception ze)
{
//must ignore local service processes on vista cause vista is mean.
fn = "c:\\dunno";
}
howFar = 2;
if (checkArgs(process[i].Id) || illegalPrograms.Contains(fn.Split(new char[] { '\\' })[fn.Split(new char[] { '\\' }).Length - 1]) || notInAllowed(fn))
{
moveFile = false;
howFar = 3;
if (illegalPrograms.Contains(fn.Split(new char[] { '\\' })[fn.Split(new char[] { '\\' }).Length - 1]))
moveFile = true;
fn = "Attempt to run: " + process[i].MainModule.FileName.ToString().Replace("\\n", "\\N") + " by " + currentUser.ToString() + " was terminated on " + System.Net.Dns.GetHostName().ToString() + ". It was opened with this command line which may be disallowed: " + getCommandLineByProcessID(process[i].Id).ToString().Replace("\\n", "\\N") + ".";
em = process[i].MainModule.FileName + " is running from an unauthorized location or is an illegal program and has been terminated. Download or installation of programs without permission is a violation of the VeraciTek ICT Acceptable Use Policy. If you are trying to run an important program please request assistance via the Help Desk.";
howFar = 4;
newName = process[i].MainModule.FileName.ToLower();
process[i].Kill();
if (moveFile)
{
System.IO.FileInfo theFile = new System.IO.FileInfo(newName);
try
{
process[i].WaitForExit(5000);
newName = System.IO.Path.GetFullPath(newName) + ".BADperVeraciTek";
if (System.IO.File.Exists(newName))
System.IO.File.Delete(newName);
theFile.MoveTo(newName);
fn += " A rename of the file to: " + newName + " has been attempted.";
em += " A rename of the file to: " + newName + " has been attempted.";
}
catch (Exception fre)
{
eLog(fre.Source + "\n" + fre.Message + "\n\n" + theFile.FullName + "--->" + newName);
fn += " Rename failed.";
em += " Rename failed.";
}
}
howFar = 5;
if (lastFileError.CompareTo(fn) != 0)
{
eLog(fn, System.Diagnostics.EventLogEntryType.Warning);
sendMessageAliased("ict", fn);
MessageBox.Show(em);
lastFileError = fn;
}
}
else
{
lastProcessList.Add(process[i].Id);
howFar = 6;
}
}
catch (Exception pe)
{
if (!pe.Message.Contains("Unable to enumerate the process modules."))
eLog(pe.Source + " got this far: " + howFar + "\n\n" + pe.Message + "\n\n" + pe.StackTrace);
//do nothing - system and system idle fail here.
}
}
}
示例10: MainLoop
//.........这里部分代码省略.........
eti.m_bIsCompleted = false;
eti.m_EncodeFileThread = thr;
eti.m_sXMLFilename = sXMLFilename;
eti.OysterProfileName = this.OysterProfileName;
eti.OysterRootDirectory = this.OysterRootDirectory;
eti.OysterSourceDirectory = this.OysterSourceDirectory;
eti.m_EventMonitor = this.m_EventMonitor;
eti.m_esi = esi;
// place filename into the thread list
ThreadList.Add(sXMLFilename,eti);
// activate the new thread
thr.Start();
//ActiveThreadCount++;
log.WriteLog("New encoding thread created. ActiveThreadCount = " + (ActiveThreadCount + 1)
+ " of " + MaxActiveThreadCount);
FAILEDFILE = "";
// endfor
}
fiFileInfoList = null;
di = null;
}
catch (System.Exception whex)
{
if (FAILEDFILE.Length > 0)
{
retrylist[FAILEDFILE] = new RetryXMLFile();
TimeSpan ts = DateTime.Now - retrylist[FAILEDFILE].LastChecked;
retrylist[FAILEDFILE].LastChecked = DateTime.Now;
if (ts.TotalSeconds > 15)
// if (retrylist[FAILEDFILE].CheckedCount++ > 5)
{
log.WriteLog(FAILEDFILE + " being renamed.");
System.IO.FileInfo fi = new System.IO.FileInfo(FAILEDFILE);
fi.MoveTo(System.IO.Path.ChangeExtension(fi.FullName,"failed"));
}
}
else
{
log.WriteLog("*ERROR* EncodeLauncher.MainLoop Exception: " + whex.Message);
log.WriteLog(" Pausing for one second before continuing...");
}
System.Threading.Thread.Sleep(1000);
}
// cleanup any completed threads
System.Collections.ArrayList al = new System.Collections.ArrayList();
foreach (string ss in ThreadList)
{
EncoderThreadItem ti = ThreadList[ss];
bool bAddIt, bAbortIt;
bAddIt = false;
bAbortIt = false;
if (ti.IsCompleted)
{
bAddIt = true;
log.WriteLog(ti.m_sXMLFilename + " is scheduled for release.");
}
else
{
try
{
// if no error on the encoder
// check for the encoder lockup by comparing the the encoding
// time right now with the encoding time save one minute ago.
if (false == ti.IsEncoderResponding(EncoderResponseTimeoutMinutes))
{
示例11: Clone
public bool Clone(bool full)
{
if (Workspace != null)
return false;
try
{
if (!full)
{
ProtoBuf.Serializer.SerializeWithLengthPrefix<NetCommand>(Connection.GetStream(), new NetCommand() { Type = NetCommandType.Clone }, ProtoBuf.PrefixStyle.Fixed32);
var clonePack = Utilities.ReceiveEncrypted<ClonePayload>(SharedInfo);
Workspace = Area.InitRemote(BaseDirectory, clonePack, SkipContainmentCheck);
}
else
{
ProtoBuf.Serializer.SerializeWithLengthPrefix<NetCommand>(Connection.GetStream(), new NetCommand() { Type = NetCommandType.FullClone }, ProtoBuf.PrefixStyle.Fixed32);
var response = ProtoBuf.Serializer.DeserializeWithLengthPrefix<NetCommand>(Connection.GetStream(), ProtoBuf.PrefixStyle.Fixed32);
if (response.Type == NetCommandType.Acknowledge)
{
int dbVersion = (int)response.Identifier;
if (!WorkspaceDB.AcceptRemoteDBVersion(dbVersion))
{
Printer.PrintError("Server database version is incompatible (v{0}). Use non-full clone to perform the operation.", dbVersion);
ProtoBuf.Serializer.SerializeWithLengthPrefix<NetCommand>(Connection.GetStream(), new NetCommand() { Type = NetCommandType.Error }, ProtoBuf.PrefixStyle.Fixed32);
return false;
}
else
ProtoBuf.Serializer.SerializeWithLengthPrefix<NetCommand>(Connection.GetStream(), new NetCommand() { Type = NetCommandType.Acknowledge }, ProtoBuf.PrefixStyle.Fixed32);
}
System.IO.FileInfo fsInfo = new System.IO.FileInfo(System.IO.Path.GetRandomFileName());
Printer.PrintMessage("Attempting to import metadata file to temp path {0}", fsInfo.FullName);
var printer = Printer.CreateSimplePrinter("Progress", (obj) =>
{
return string.Format("#b#{0}## received.", Versionr.Utilities.Misc.FormatSizeFriendly((long)obj));
});
try
{
long total = 0;
using (var stream = fsInfo.OpenWrite())
{
while (true)
{
var data = Utilities.ReceiveEncrypted<DataPayload>(SharedInfo);
stream.Write(data.Data, 0, data.Data.Length);
total += data.Data.Length;
printer.Update(total);
if (data.EndOfStream)
break;
}
printer.End(total);
response = ProtoBuf.Serializer.DeserializeWithLengthPrefix<NetCommand>(Connection.GetStream(), ProtoBuf.PrefixStyle.Fixed32);
if (response.Type == NetCommandType.Error)
{
Printer.PrintError("Server failed to clone the database.");
return false;
}
}
Printer.PrintMessage("Metadata written, importing DB.");
Area area = new Area(Area.GetAdminFolderForDirectory(BaseDirectory));
try
{
fsInfo.MoveTo(area.MetadataFile.FullName);
if (!area.ImportDB())
throw new Exception("Couldn't import data.");
Workspace = Area.Load(BaseDirectory);
SharedInfo.Workspace = Workspace;
return true;
}
catch
{
if (area.MetadataFile.Exists)
area.MetadataFile.Delete();
area.AdministrationFolder.Delete();
throw;
}
}
catch
{
if (fsInfo.Exists)
fsInfo.Delete();
return false;
}
}
SharedInfo.Workspace = Workspace;
return true;
}
catch (Exception e)
{
Printer.PrintError(e.ToString());
return false;
}
}
示例12: moveFiles
private void moveFiles(string SourceDirectory, string DestinationDirectory, bool Overwrite)
{
System.IO.DirectoryInfo DestinationDirInfo = new System.IO.DirectoryInfo(DestinationDirectory);
//Create destination if it does not already exist
if (DestinationDirInfo.Exists == false) System.IO.Directory.CreateDirectory(DestinationDirectory);
//Get list of files to move
List<string> SourceFiles = System.IO.Directory.GetFiles(SourceDirectory,"*.*").ToList();
foreach(string file in SourceFiles)
{
System.IO.FileInfo SourceFileInfo = new System.IO.FileInfo(file);
if ((new System.IO.FileInfo(DestinationDirInfo + "\\" + SourceFileInfo.Name).Exists == true) && (Overwrite == true))
{
System.IO.File.Delete(DestinationDirInfo + "\\" + SourceFileInfo.Name);
}
SourceFileInfo.MoveTo(DestinationDirInfo + "\\" + SourceFileInfo.Name);
}
}
示例13: Encode
//.........这里部分代码省略.........
// stop all activity so that all files are released
m_wme.PrepareToEncode(false);
// now explicitly get rid of the Encoder objects.
m_wme = null;
// enable the video within the Oyster Player
try
{
o = new OysterClassLibrary.Oyster();
}
catch (System.Exception oex)
{
sError = "*ERROR* Encode: When attempting to open the OysterClassLibrary and exception occured: " + oex.Message;
goto Encode_Err;
}
OysterClassLibrary.Recording rec = o.GetRecordingByName(sBaseFilename + ".wmv");
if (null == rec)
{
log.WriteLog(sBaseFilename + ".wmv: *ERROR* not found in database. Nothing to enable.");
}
else
{
rec.IsReady = true;
rec = null;
}
// end routine
goto Encode_Exit;
Encode_Err:
m_bFailed = true;
// log.WriteLog(sError);
if (m_bStartupFailed)
{
goto Encode_Startup_Err;
}
m_EventMonitor.WaitOne(10000,false);
m_esi.AddError(m_sUniqueIdentifier,sError);
m_EventMonitor.Set();
try
{
if (null != m_wme && !m_bEmergencyStop && !m_bStartupFailed)
{
log.WriteLog(sBaseFilename + ":Shutting down encoder");
m_wme.PrepareToEncode(false);
log.WriteLog(sBaseFilename + ":Encoder is shut down.");
}
}
catch
{
log.WriteLog(sBaseFilename + ":Encoder failed to shut down.");
}
Encode_Startup_Err:
m_EventMonitor.WaitOne(10000,false);
EncodeLauncher.ErrorRenameXML(null,m_sXMLFilename,sError,log,m_bStartupFailed);
if (!EncodeLauncher.ResetReqursted)
{
System.Net.IPEndPoint ep = new System.Net.IPEndPoint(System.Net.Dns.Resolve(Environment.MachineName).AddressList[0],22580);
System.Net.Sockets.UdpClient u = new System.Net.Sockets.UdpClient(System.Net.Sockets.AddressFamily.InterNetwork);
string s = "reset";
u.Send(System.Text.ASCIIEncoding.ASCII.GetBytes(s),s.Length,ep);
log.WriteLog(sBaseFilename + ":Requested a reset...");
EncodeLauncher.ResetReqursted = true;
}
m_EventMonitor.Set();
Encode_Exit:
m_wme = null;
// mark the thread as complete in the global array list of threads
m_bIsCompleted = true;
EncodeLauncher.ActiveThreadCount--;
log.WriteLog(m_sXMLFilename + ": encoding thread destroyed. ActiveThreadCount = " + EncodeLauncher.ActiveThreadCount
+ " of " + EncodeLauncher.MaxActiveThreadCount);
}
catch (System.Exception encex)
{
CarverLabUtility.Logger.WriteLog("EncodingService","EncoderThreadItem.Encode " + m_sXMLFilename + ": Exception thrown on outer try/catch: " + encex.Message);
m_bIsCompleted = true;
m_bFailed = true;
m_wme = null;
GC.Collect();
//GC.WaitForPendingFinalizers();
System.IO.FileInfo fi = new System.IO.FileInfo(m_sXMLFilename);
m_EventMonitor.WaitOne(10000,false);
fi.MoveTo(System.IO.Path.ChangeExtension(m_sXMLFilename,"catastrophic.err"));
//System.IO.File.Move(m_sXMLFilename, m_sXMLFilename + ".catastrophic.err");
EncodeLauncher.ActiveThreadCount--;
if (!EncodeLauncher.ResetReqursted)
{
System.Net.IPEndPoint ep = new System.Net.IPEndPoint(System.Net.Dns.Resolve(Environment.MachineName).AddressList[0],22580);
System.Net.Sockets.UdpClient u = new System.Net.Sockets.UdpClient(System.Net.Sockets.AddressFamily.InterNetwork);
string s = "reset";
u.Send(System.Text.ASCIIEncoding.ASCII.GetBytes(s),s.Length,ep);
log.WriteLog(m_sXMLFilename + ":Requested a reset...");
EncodeLauncher.ResetReqursted = true;
}
m_EventMonitor.Set();
}
}
示例14: Save
public void Save(string dir)
{
Save();
System.IO.FileInfo fiCurrentPath = new System.IO.FileInfo(dataPath);
string name = fiCurrentPath.Name;
fiCurrentPath.MoveTo(dir + "\\" + name);
dataPath = fiCurrentPath.FullName;
}
示例15: CopyExtractedFiles
private void CopyExtractedFiles( string root )
{
foreach ( string item in BareBonesBackupConfiguration.Instance.Files ) {
string tstring = item;
if ( tstring.StartsWith ( root ) ) {
tstring = tstring.Remove ( 0, root.Length );
}
string tlocal = item;
if ( tlocal.StartsWith ( "/" ) ) {
tlocal = tlocal.Remove ( 0, 1 );
}
System.IO.FileInfo ofile = new System.IO.FileInfo ( System.IO.Path.Combine ( CommandRunner.Instance.TempDataPath, tstring ) );
if ( ofile.Exists ) {
System.IO.FileInfo nfile = new System.IO.FileInfo ( System.IO.Path.Combine ( UpdateTempPath, tlocal ) );
if ( !nfile.Directory.Exists ) {
nfile.Directory.Create ( );
}
string statusString = string.Format ( CultureInfo.InvariantCulture, "Copying {0}", nfile.Name );
if ( this.InvokeRequired ) {
this.Invoke ( new SetControlTextDelegate ( SetControlText ), status, statusString );
} else {
SetControlText ( status, statusString );
}
ofile.MoveTo ( nfile.FullName );
}
}
}