Create() private method

private Create ( ) : void
return void
Esempio n. 1
1
        public static void Resize(this Image source, String newFilename, Size newSize, long quality, ContentAlignment contentAlignment, ThumbMode mode)
        {
            Image image = source.Resize(newSize, quality, contentAlignment, mode);

            using (EncoderParameters encoderParams = new EncoderParameters(1))
            {
                using (EncoderParameter parameter = (encoderParams.Param[0] = new EncoderParameter(Encoder.Quality, quality)))
                {
                    ImageCodecInfo encoder = null;
                    //取得擴展名
                    string ext = Path.GetExtension(newFilename);
                    if (string.IsNullOrEmpty(ext))
                        ext = ".jpg";
                    //根據擴展名得到解碼、編碼器
                    foreach (ImageCodecInfo codecInfo in ImageCodecInfo.GetImageEncoders())
                    {
                        if (Regex.IsMatch(codecInfo.FilenameExtension, string.Format(@"(;|^)\*\{0}(;|$)", ext), RegexOptions.IgnoreCase))
                        {
                            encoder = codecInfo;
                            break;
                        }
                    }

                    DirectoryInfo dir = new DirectoryInfo(Path.GetDirectoryName(newFilename));
                    if(dir.Exists == false) dir.Create();
                    image.Save(newFilename, encoder, encoderParams);
                }
            }
        }
Esempio n. 2
1
        protected void btnUpload_Click(object sender, EventArgs e)
        {
            lb_notvalid.Visible = false;

            if (FileUpload1.HasFile)
            {
                Guid g = Guid.NewGuid();
                DirectoryInfo updir = new DirectoryInfo(Server.MapPath("/media/upload/" + g));

                if (!updir.Exists)
                    updir.Create();

                FileUpload1.SaveAs(updir.FullName + "/" + FileUpload1.FileName);

                if (IsValidImage(updir.FullName + "/" + FileUpload1.FileName))
                {

                    tb_url.Text = "/media/upload/" + g + "/" +
                        ResizeImage(updir.FullName + "/", FileUpload1.FileName,
                        500, 1000, true);
                }
                else
                {
                    lb_notvalid.Visible = true;
                }
            }
        }
Esempio n. 3
1
 private static void CreateDirectoryIfNotExists(DirectoryInfo directoryInfo)
 {
     if(!directoryInfo.Exists) {
         CreateDirectoryIfNotExists(directoryInfo.Parent);
         directoryInfo.Create();
     }
 }
        public JsonResult AtualizarGaleiraFotos(string galeriaFotosUID,int IdProduto)
        {
            var direcotryTemp = new DirectoryInfo(Server.MapPath(string.Concat(ConfigurationManager.AppSettings["CaminhoImagensProduto"],"/temp/", galeriaFotosUID)));
            var directoryProd = new DirectoryInfo(Server.MapPath(string.Concat(ConfigurationManager.AppSettings["CaminhoImagensProduto"],"/", IdProduto.ToString())));

            if (!directoryProd.Exists)
                directoryProd.Create();
            else
            {
                directoryProd.Delete(true);
                directoryProd.Create();
            }

            foreach(var ft in direcotryTemp.GetFiles())
            {
                var newFile = string.Concat(directoryProd.FullName,"\\",ft.Name);
                ft.MoveTo(newFile);
            }

            direcotryTemp.Delete(true);

            return Json(new
            {
                TipoMensagem = TipoMensagemRetorno.Ok,
                Mensagem = "Operação Realizada com sucesso!",
            }, "text/html", JsonRequestBehavior.AllowGet);
        }
 public static void RecreateFolder(DirectoryInfo directoryInfo)
 {
     if (!directoryInfo.Exists)
     {
         directoryInfo.Create();
     }
     else
     {
         directoryInfo.Delete(true);
         directoryInfo.Create();
     }
 }
Esempio n. 6
0
		public void EntriesSetup()
		{
			createEntries = new DirectoryInfo(Path.Combine(this.testContent.FullName, "CreateEntries"));
			// delete old entries
			if (createEntries.Exists)
			{
				createEntries.Delete(true);
				createEntries.Create();
			}
			else
			{
				createEntries.Create();
			}
		}
    public static string DownloadAppFiles(string PathAndName)
    {
        string strStatus = "";

        string[] strFileListing;
        string   strSimpleFileName;
        string   strAppName;
        Int32    intIndex;

        intIndex   = PathAndName.LastIndexOf("\\");
        strAppName = PathAndName.Substring(intIndex + 1);
        try {
            System.IO.DirectoryInfo DI = new System.IO.DirectoryInfo("c:\\" + strAppName);
            if (!(DI.Exists))
            {
                DI.Create();
            }
            strFileListing = System.IO.Directory.GetFiles(PathAndName);
            foreach (string strFullFileName in strFileListing)
            {
                intIndex          = strFullFileName.LastIndexOf("\\");
                strSimpleFileName = strFullFileName.Substring(intIndex + 1);
                System.IO.File.Copy(strFullFileName, "c:\\" + strAppName + "\\" + strSimpleFileName, true);
            }
            strStatus = "Completed";
        } catch (Exception ex) {
            Console.WriteLine(ex.ToString() + "\r\n" + "Press any key to continue...");
            Console.ReadLine();
            strStatus = "Failed";
        }
        return(strStatus);
    }
Esempio n. 8
0
    private static void chat(string StartupPath, string msg)
    {
        string FileName = DateTime.Now.ToString("yyyyMMdd");
        string sPath    = null;
        string filePath;

        sPath = StartupPath;

        System.IO.DirectoryInfo oDir = new System.IO.DirectoryInfo(sPath);
        if (!oDir.Exists)
        {
            oDir.Create();
        }
        filePath = sPath + "\\\\" + FileName + ".log";

        //System.IO.StreamWriter sw = new System.IO.StreamWriter(filePath, true, System.Text.Encoding.GetEncoding("Big5"));
        System.IO.StreamWriter sw = new System.IO.StreamWriter(filePath, true, System.Text.Encoding.GetEncoding("utf-8"));
        //System.IO.StreamWriter sw = new System.IO.StreamWriter(filePath, true, System.Text.Encoding.GetEncoding("Unicode"));

        sw.WriteLine(DateTime.Now.ToShortTimeString() + "  " + msg);
        sw.Close();

        //if (IsDebug)
        //    //叫出記事本
        //    System.Diagnostics.Process.Start(filePath);
    }
Esempio n. 9
0
    ///<summary>
    ///log
    ///     </summary>
    ///<param name="StartupPath">儲存的目錄位置</param>
    ///<param name="ErrorMsg">訊息</param>
    ///<param name="ErrorMsg">FileName</param>
    public static void log(string StartupPath, string msg, string FileName)
    {
        string sPath = null;
        string filePath;

        if (StartupPath == "")
        {
            StartupPath = System.IO.Directory.GetCurrentDirectory();
        }

        sPath = StartupPath;

        System.IO.DirectoryInfo oDir = new System.IO.DirectoryInfo(sPath);
        if (!oDir.Exists)
        {
            oDir.Create();
        }
        filePath = sPath + "\\\\" + DateTime.Now.ToString("yyyyMMdd") + FileName + ".log";

        //System.IO.StreamWriter sw = new System.IO.StreamWriter(filePath, true, System.Text.Encoding.GetEncoding("Big5"));
        //System.IO.StreamWriter sw = new System.IO.StreamWriter(filePath, true, System.Text.Encoding.GetEncoding("utf-8"));
        System.IO.StreamWriter sw = new System.IO.StreamWriter(filePath, true, System.Text.Encoding.GetEncoding("Unicode"));

        sw.WriteLine(DateTime.Now.ToString() + " --" + msg);
        sw.Close();

        //if (IsDebug)
        //    //叫出記事本
        //    System.Diagnostics.Process.Start(filePath);
    }
Esempio n. 10
0
    void OnEnable()
    {
#if !UNITY_EDITOR
        // If the xml configuration file does not exists, create it
        if (!ReadXml(xmlConfigFolder + @"Lens.xml"))
        {
            System.IO.DirectoryInfo lensDir = new System.IO.DirectoryInfo(xmlConfigFolder);
            if (!lensDir.Exists)
            {
                lensDir.Create();
            }
            WriteXml(xmlConfigFolder + @"Lens.xml");
        }
#endif

        string filePath = xmlConfigFolder + fileName;

        if (lens.ReadFile(filePath, computeFovFromMatrix))
        {
            if (SystemInfo.graphicsDeviceVersion.Contains("OpenGL"))
            {
                StartCoroutine(UpdateDistortionMap());
            }
        }
        else
        {
            Debug.LogError("Could not open lens file: " + filePath);
        }
    }
 private void ensureExists(DirectoryInfo toDir)
 {
     if (toDir.Exists == false)
     {
         toDir.Create();
     }
 }
    IEnumerator SaveBundleCR(string abName, byte[] bytes)
    {
        Debug.Log("Saving bundle '" + abName + "' (" + bytes.Length + " bytes)");

        System.IO.DirectoryInfo bundleDirInfo = new System.IO.DirectoryInfo(AppManager.persistentBundlePath);
        if (!bundleDirInfo.Exists)
        {
            Debug.Log("Creating persistent bundle dir " + AppManager.persistentBundlePath);
            bundleDirInfo.Create( );
            bundleDirInfo = new System.IO.DirectoryInfo(AppManager.persistentBundlePath);
            if (!bundleDirInfo.Exists)
            {
                Debug.Log("Failed to create persistent bundle dir ");
                yield break;
            }
        }

        string saveBundleFilename = AppManager.persistentBundlePath + abName;

        System.IO.FileInfo bundleFileInfo = new System.IO.FileInfo(saveBundleFilename);
        if (bundleFileInfo.Exists)
        {
            Debug.LogWarning("Bundle File " + saveBundleFilename + " exists, will overwrite");
        }
        else
        {
            Debug.Log("Creating File " + saveBundleFilename);
        }

        System.IO.File.WriteAllBytes(saveBundleFilename, bytes);
        Debug.Log("Created File " + saveBundleFilename);

        yield return(null);
    }
Esempio n. 13
0
        static void Main(string[] args)
        {
            var firstDirectoryPath = @"C:\ProgrammingInCSharpDirectory";
            var secondDirectoryPath = @"C:\ProgrammingInCSharpDirectoryInfo";
            var diretory = Directory.CreateDirectory(firstDirectoryPath);
            Console.WriteLine("Created diretory: {0}", firstDirectoryPath);

            var diretoryInfo = new DirectoryInfo(secondDirectoryPath);
            diretoryInfo.Create();
            Console.WriteLine("Created diretory: {0}", secondDirectoryPath);
            Console.Write("Press 'Enter' to delete the created folders: ");
            ConsoleKeyInfo cki = Console.ReadKey(true);
            if (cki.Key == ConsoleKey.Enter)
            {
                if (Directory.Exists(firstDirectoryPath))
                {
                    Directory.Delete(firstDirectoryPath);
                    Console.WriteLine();
                    Console.WriteLine("Deleted: {0}", firstDirectoryPath);
                }

                if (diretoryInfo.Exists)
                {
                    diretoryInfo.Delete();
                    Console.WriteLine("Deleted: {0}", secondDirectoryPath);
                }
            }
            else
            {
                Console.WriteLine("Created folders were not deleted");
            }

            Console.Write("Press a key to exit ... ");
            Console.ReadKey();
        }
Esempio n. 14
0
        /// <summary>
        /// Recursively copies a directory.
        /// </summary>
        /// <param name="sourceDirectory">The source directory to copy.</param>
        /// <param name="destinationDirectory">The destination directory.</param>
        /// <returns><see langword="true"/> if the copy is completed; otherwise <see langword="false"/>.</returns>
        public static bool CopyDirectory(string sourceDirectory, string destinationDirectory)
        {
            bool copyComplete = false;
            DirectoryInfo sourceDirectoryInfo = new DirectoryInfo(sourceDirectory);
            DirectoryInfo destinationDirectoryInfo = new DirectoryInfo(destinationDirectory);

            if (sourceDirectoryInfo.Exists)
            {
                if (!destinationDirectoryInfo.Exists)
                {
                    destinationDirectoryInfo.Create();
                }

                foreach (FileInfo fileEntry in sourceDirectoryInfo.GetFiles())
                {
                    fileEntry.CopyTo(Path.Combine(destinationDirectoryInfo.FullName, fileEntry.Name));
                }

                foreach (DirectoryInfo directoryEntry in sourceDirectoryInfo.GetDirectories())
                {
                    if (!CopyDirectory(directoryEntry.FullName, Path.Combine(destinationDirectoryInfo.FullName, directoryEntry.Name)))
                    {
                        copyComplete = false;
                    }
                }
            }

            copyComplete = true;
            return copyComplete;
        }
    // Move file to destination directory and create the directory when none exists.
    public static void MoveFileToDirectory(string srcFilePath, string destDir)
    {
        var fi = new System.IO.FileInfo(srcFilePath);

        if (!fi.Exists)
        {
            UnityEngine.Debug.LogError(string.Format("WwiseUnity: Failed to move. Source is missing: {0}.", srcFilePath));
            return;
        }

        var di = new System.IO.DirectoryInfo(destDir);

        if (!di.Exists)
        {
            di.Create();
        }

        string destFilePath = System.IO.Path.Combine(di.FullName, fi.Name);

        try
        {
            fi.MoveTo(destFilePath);
        }
        catch (Exception ex)
        {
            UnityEngine.Debug.LogError(string.Format("WwiseUnity: Error during installation: {0}.", ex.Message));
            return;
        }

        return;
    }
    // Copy or overwrite destination file with source file.
    public static bool OverwriteFile(string srcFilePath, string destFilePath)
    {
        var fi = new System.IO.FileInfo(srcFilePath);

        if (!fi.Exists)
        {
            UnityEngine.Debug.LogError(string.Format("WwiseUnity: Failed to overwrite. Source is missing: {0}.", srcFilePath));
            return(false);
        }

        var di = new System.IO.DirectoryInfo(System.IO.Path.GetDirectoryName(destFilePath));

        if (!di.Exists)
        {
            di.Create();
        }

        const bool IsToOverwrite = true;

        try
        {
            fi.CopyTo(destFilePath, IsToOverwrite);
        }
        catch (Exception ex)
        {
            UnityEngine.Debug.LogError(string.Format("WwiseUnity: Error during installation: {0}.", ex.Message));
            return(false);
        }

        return(true);
    }
Esempio n. 17
0
    public static void KachiLib_BasicFolder_3D()
    {
        string[] folderList =
        {
            "Scenes",
            "Resources/Global",
            "Resources/Global/Scripts",
            "Resources/Global/Images",
            "Resources/Global/Models",
            "Resources/Global/Shaders",
            "Resources/Global/Animations",
            "Resources/Global/Sounds",
            "Resources/Global/Fonts",
            "Resources/Global/Materials",
            "Resources/Global/Prefabs",
        };

        for (int i = 0; i < folderList.Length; i++)
        {
            System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(Application.dataPath + "/" + folderList[i]);

            if (!di.Exists)
            {
                di.Create();
            }
        }

        EditorApplication.update();
        AssetDatabase.Refresh();
    }
Esempio n. 18
0
 private void CopyFolder(string from, string to)
 {
     try
     {
         DirectoryInfo source = new DirectoryInfo(from);
         DirectoryInfo destination = new DirectoryInfo(to);
         string fullpath;
         if (!destination.Exists)
             destination.Create();
         FileInfo[] Files = source.GetFiles();
         foreach (FileInfo fi in Files)
         {
             fullpath = Path.Combine(destination.FullName, fi.Name);
             fi.CopyTo(fullpath, true);
             this.counter++;
             int p = (this.counter * 100) / this.total;
             this.Worker.ReportProgress(p, fullpath);
         }
         // for subfolders
         DirectoryInfo[] folders = source.GetDirectories();
         foreach (DirectoryInfo folder in folders)
         {
             //construct new destination
             string newdestination = Path.Combine(destination.FullName, folder.Name);
             //recursive CopyFolder()
             CopyFolder(folder.FullName, newdestination);
         }
     }
     catch (Exception e)
     {
         Exceptioner.Log(e);
     }
 }
Esempio n. 19
0
        protected void CreateFolder()
        {
            try
            {

                string Serverpath = System.Configuration.ConfigurationManager.AppSettings["FolderPath"];
                string sDirPath = Server.MapPath("/"+Serverpath+"/");
                DirectoryInfo ObjSearchDir = new DirectoryInfo(sDirPath);

                if (!ObjSearchDir.Exists)
                {
                    ObjSearchDir.Create();
                    //Random number folder for file uploading

                    hdnUploadFilePath.Value = sDirPath;
                }
                else
                {
                    hdnUploadFilePath.Value = sDirPath;
                    // hdnFileFolder.Value = "0";
                }

            }
            catch (Exception mEx)
            {

            }
        }
Esempio n. 20
0
    public void CreateAssetInFolder(Object newAsset, string ParentFolder, string AssetName)
    {
        System.IO.DirectoryInfo dirInfo = new System.IO.DirectoryInfo(string.Format("{0}/{1}", Application.dataPath, ParentFolder));
        dirInfo.Create();

        AssetDatabase.CreateAsset(newAsset, string.Format("Assets/{0}/{1}.asset", ParentFolder, AssetName));
    }
Esempio n. 21
0
        public static void InsertMsg(string msg)
        {
            //锁住写日文对象,防止多线程同时写文件,造成并发。
            //Update by Chen De Jun 2013-10-8
            lock (_fileLockObj)
            {
                var dt = DateTime.Now;
                var di = new DirectoryInfo(Application.StartupPath + "\\" + DirectPath);
                if (di.Exists == false) di.Create();
                var disub = new DirectoryInfo(di.ToString() + "\\" + dt.ToString("yyyy-MM"));
                if (disub.Exists == false) disub.Create();

                //每天生成一个文件,会造成文件容易增加,减慢效率。故意每天每小时生成一个文件。 
                //Update by Chen De Jun 2013-10-8
                var filePath = disub.ToString() + "\\" + dt.ToString("yyyy-MM-dd HH") + ".txt";

                if (!File.Exists(filePath))
                {
                    FileStream fs = File.Create(filePath);//防止产生“另一个进程访问”出错,不能直接Create
                    fs.Flush();
                    fs.Close();
                }
                var filestream = new System.IO.FileStream(filePath, System.IO.FileMode.Append, System.IO.FileAccess.Write, FileShare.ReadWrite);
                var sw = new StreamWriter(filestream, Encoding.GetEncoding("gb2312"));
                //File.AppendText(FilePath);
                sw.WriteLine(msg);
                sw.Flush();
                sw.Close();
            }
        }
Esempio n. 22
0
        public static void CopyFiles(string sourceFolder, string targetFolder, bool recursive)
        {
            if (sourceFolder == null)
                throw new ArgumentNullException(@"C:/Source");
            if (targetFolder == null)
                throw new ArgumentNullException(@"C:/Target");

            DirectoryInfo sourced = new DirectoryInfo(sourceFolder);
            DirectoryInfo targetd = new DirectoryInfo(targetFolder);

            if (!sourced.Exists)
                sourced.Create();

            foreach (FileInfo file in sourced.GetFiles())
            {
                file.CopyTo(Path.Combine(targetd.FullName, file.Name), true);
            }

            if (!recursive) 
                return;

            foreach (DirectoryInfo directory in sourced.GetDirectories())
            {
                CopyFiles(directory.FullName, Path.Combine(targetd.FullName, directory.Name), recursive);
            }
        }
Esempio n. 23
0
        public void DumpData()
        {
            List<Microsoft.Research.Kinect.Nui.Vector> verts = convertRealDepth();
            DirectoryInfo root = new DirectoryInfo("./Dump");
            if(!root.Exists){
                root.Create();
            }

            int ct = 1;
            FileInfo file = new FileInfo(root.FullName + "/" + "dump_0.obj");
            while(file.Exists){
                file = new FileInfo(root.FullName + "/" + "dump_" + ct.ToString() + ".obj");
                ct++;
            }
            Console.WriteLine("Mesh Saved: {0}",file.FullName);
            List<Microsoft.Research.Kinect.Nui.Vector> tmp = new List<Microsoft.Research.Kinect.Nui.Vector>(points);
            using (StreamWriter sw = new StreamWriter(file.FullName))
            {
                foreach (Microsoft.Research.Kinect.Nui.Vector v in tmp)
                {
                    sw.WriteLine("v " + v.X.ToString() + " " + v.Y.ToString() + " " + v.Z.ToString());
                }

            }
        }
Esempio n. 24
0
 public bool Initialize(DirectoryInfo directory, Random r, out string reason)
 {
     try
     {
         string path = Path.Combine(directory.FullName, "races");
         DirectoryInfo di = new DirectoryInfo(path);
         if (!di.Exists)
         {
             //If it don't exist, create one so users can add races
             di.Create();
         }
         foreach (FileInfo fi in di.GetFiles("*.xml"))
         {
             Race race = new Race();
             if (!race.Initialize(fi, r, out reason))
             {
                 return false;
             }
             Races.Add(race);
         }
         reason = null;
         return true;
     }
     catch (Exception e)
     {
         reason = e.Message;
         return false;
     }
 }
Esempio n. 25
0
    private string GetDocumentPath(int intFileType)
    {
        string uploadFolder, strFolder = "";

        System.IO.DirectoryInfo di;

        switch (intFileType)
        {
        case 1:
            strFolder = "Photos";
            break;

        case 2:
            strFolder = "Videos";
            break;

        case 3:
            strFolder = "Documents";
            break;
        }

        uploadFolder = System.IO.Path.Combine(this.Context.ApplicationInstance.Request.PhysicalApplicationPath, strFolder);

        di = new System.IO.DirectoryInfo(uploadFolder);
        if (di.Exists == false) // Create the directory only if it does not already exist.
        {
            di.Create();
        }
        return(uploadFolder);
    }
    // 파티클 저장
    void OnApplicationQuit()
    {
        string path = Application.streamingAssetsPath + "/" + MovieName;

        System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(path);
        if (!di.Exists)
        {
            di.Create();
        }

        System.Xml.XmlDocument Document      = new System.Xml.XmlDocument();
        System.Xml.XmlElement  MovieDataList = Document.CreateElement("MovieDataList");
        Document.AppendChild(MovieDataList);

        foreach (var it in recoderQueue)
        {
            // 경로 지정
            it.Save(Document, MovieDataList);
        }
        recoderQueue.Clear();

        path = Application.streamingAssetsPath + "/Movie/" + MovieName + ".xml";

#if !NETFX_CORE
        Document.Save(path);
#endif
    }
    // 파티클 저장
    void OnApplicationQuit()
    {
        string path = Application.streamingAssetsPath + "/" + MovieName;

        System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(path);
        if (!di.Exists)
        {
            di.Create();
        }

        System.Xml.XmlDocument Document      = new System.Xml.XmlDocument();
        System.Xml.XmlElement  MovieDataList = Document.CreateElement("MovieDataList");
        Document.AppendChild(MovieDataList);

        for (int i = 0; i < effectRecoderObjects.Count; i++)
        {
            // 경로 지정
            effectRecoderObjects[i].Save(Document, MovieDataList);
        }
        effectRecoderObjects.Clear();

        path = Application.streamingAssetsPath + "/Movie/" + MovieName + "Object.xml";

#if !NETFX_CORE
        Document.Save(path);
#endif
    }
Esempio n. 28
0
        private static void DirectoryCopy(string sourcePath, string destinationPath)
        {
            DirectoryInfo sourceDirectory = new DirectoryInfo(sourcePath);
            DirectoryInfo destinationDirectory = new DirectoryInfo(destinationPath);

            //コピー先のディレクトリがなければ作成する
            if (destinationDirectory.Exists == false)
            {
                destinationDirectory.Create();
                destinationDirectory.Attributes = sourceDirectory.Attributes;
            }

            //ファイルのコピー
            foreach (FileInfo fileInfo in sourceDirectory.GetFiles())
            {
                //同じファイルが存在していたら、常に上書きする
                fileInfo.CopyTo(destinationDirectory.FullName + @"\" + fileInfo.Name, true);
            }

            //ディレクトリのコピー(再帰を使用)
            foreach (System.IO.DirectoryInfo directoryInfo in sourceDirectory.GetDirectories())
            {
                DirectoryCopy(directoryInfo.FullName, destinationDirectory.FullName + @"\" + directoryInfo.Name);
            }
        }
Esempio n. 29
0
        public void SetVariable(string variableName, object value)
        {
            // the folder to hold variable info (type and value)
            DirectoryInfo variableFolder = new DirectoryInfo(VarDir.FullName + @"\" + SpecialSymbols.Encode(variableName));

            if (!variableFolder.Exists)
                variableFolder.Create();

            foreach (DirectoryInfo subdir in variableFolder.GetDirectories())
            {
                subdir.Delete();
            }

            // variable type (first subdirectory -- we will label with 1 to be sure)
            variableFolder.CreateSubdirectory("1 " + SpecialSymbols.Encode(value.GetType().ToString()));

            // if it's a string more than our max folder size, we'll break it down into sections
            if (value.ToString().Length > MAX_FOLDER_SIZE)
            {
                int folderNum = 2;

                foreach (string substring in SplitByLength(value.ToString(), MAX_FOLDER_SIZE))
                {
                    variableFolder.CreateSubdirectory(folderNum.ToString() + " " + SpecialSymbols.Encode(substring));
                    folderNum++;
                }
            }
            else
            {
                variableFolder.CreateSubdirectory("2 " + SpecialSymbols.Encode(value.ToString()));
            }
        }
Esempio n. 30
0
 private void Awake()
 {
     DontDestroyOnLoad(this);
     m_Instance = this;
     m_Material = Resources.Load <Material>("Plane_No_zTest");
             #if UNITY_EDITOR
     if (m_Material == null)
     {
         var resDir = new System.IO.DirectoryInfo(System.IO.Path.Combine(Application.dataPath, "Resources"));
         if (!resDir.Exists)
         {
             resDir.Create();
         }
         Shader s = Shader.Find("Plane/No zTest");
         if (s == null)
         {
             string shaderText = "Shader \"Plane/No zTest\" { SubShader { Pass { Blend SrcAlpha OneMinusSrcAlpha ZWrite Off Cull Off Fog { Mode Off } BindChannels { Bind \"Color\",color } } } }";
             string path       = System.IO.Path.Combine(resDir.FullName, "Plane_No_zTest.shader");
             Debug.Log("Shader missing, create asset: " + path);
             System.IO.File.WriteAllText(path, shaderText);
             UnityEditor.AssetDatabase.Refresh(UnityEditor.ImportAssetOptions.ForceSynchronousImport);
             UnityEditor.AssetDatabase.LoadAssetAtPath <Shader>("Resources/Plane_No_zTest.shader");
             s = Shader.Find("Plane/No zTest");
         }
         var mat = new Material(s);
         mat.name = "Plane_No_zTest";
         UnityEditor.AssetDatabase.CreateAsset(mat, "Assets/Resources/Plane_No_zTest.mat");
         m_Material = mat;
     }
             #endif
 }
Esempio n. 31
0
 /// <summary>
 /// Creates the directory for writing test files. We use the %TEMP% directory here.
 /// </summary>
 /// <param name="folder">The folder.</param>
 /// <returns></returns>
 public static DirectoryInfo CreateDirectory(string folder)
 {
     var path = //Environment.CurrentDirectory;
         Path.Combine(Path.GetTempPath(), "DatabaseSchemaReader");
     var directory = new DirectoryInfo(path);
     if (!directory.Exists)
     {
         directory.Create();
     }
     if (directory.GetDirectories(folder).Any())
     {
         //if it's already there, clear it out
         var sub = directory.GetDirectories(folder).First();
         try
         {
             sub.Delete(true);
         }
         catch (UnauthorizedAccessException)
         {
             //can't access it, carry on
         }
     }
     var subdirectory = directory.CreateSubdirectory(folder);
     //because it may not actually have been created...
     if (!subdirectory.Exists)
         subdirectory.Create();
     return subdirectory;
 }
Esempio n. 32
0
		public async Task PeriodicBackup_should_export_all_relevant_documents()
		{
			var existingData = new List<DummyDataEntry>();
			var backupFolder = new DirectoryInfo(Path.GetTempPath() + "\\periodic_backup_" + Guid.NewGuid());
			if (!backupFolder.Exists)
				backupFolder.Create();

			documentStore.DatabaseCommands.GlobalAdmin.CreateDatabase(new DatabaseDocument
			{
				Id = "SourceDB",
				Settings =
				{
					{"Raven/ActiveBundles", "PeriodicBackup"},
					{"Raven/DataDir", "~\\Databases\\SourceDB"}
				}
			});

			documentStore.DatabaseCommands.GlobalAdmin.CreateDatabase(new DatabaseDocument
			{
				Id = "DestDB",
				Settings = {{"Raven/DataDir", "~\\Databases\\DestDB"}}
			});
			//setup periodic export
			using (var session = documentStore.OpenSession("SourceDB"))
			{
				session.Store(new PeriodicExportSetup {LocalFolderName = backupFolder.FullName, IntervalMilliseconds = 500},
					PeriodicExportSetup.RavenDocumentKey);
				session.SaveChanges();
			}

			//now enter dummy data
			using (var session = documentStore.OpenSession())
			{
				for (int i = 0; i < 10000; i++)
				{
					var dummyDataEntry = new DummyDataEntry {Id = "Dummy/" + i, Data = "Data-" + i};
					existingData.Add(dummyDataEntry);
					session.Store(dummyDataEntry);
				}
				session.SaveChanges();
			}

			var connection = new RavenConnectionStringOptions {Url = documentStore.Url, DefaultDatabase = "DestDB"};
            var smugglerApi = new SmugglerDatabaseApi { Options = { Incremental = true } };
            await smugglerApi.ImportData(new SmugglerImportOptions<RavenConnectionStringOptions> { FromFile = backupFolder.FullName, To = connection });

			using (var session = documentStore.OpenSession())
			{
				var fetchedData = new List<DummyDataEntry>();
				using (var streamingQuery = session.Advanced.Stream<DummyDataEntry>("Dummy/"))
				{
					while (streamingQuery.MoveNext())
						fetchedData.Add(streamingQuery.Current.Document);
				}

				Assert.Equal(existingData.Count, fetchedData.Count);
				Assert.True(existingData.Select(row => row.Data).ToHashSet().SetEquals(fetchedData.Select(row => row.Data)));
			}

		}
Esempio n. 33
0
        static void Main(string[] args)
        {
            string path = Environment.CurrentDirectory;
            string newdirpath = "";
            DirectoryInfo dirInfo = new DirectoryInfo(path);
            Console.WriteLine(dirInfo.FullName);

            for (int i = 0; i < 2; i++)
            {
                newdirpath = path + @"\mydir" + i;
                dirInfo = new DirectoryInfo(newdirpath);
                if (!dirInfo.Exists)
                {
                    dirInfo.Create();
                }
            }

            for (int i = 0; i < 2; i++)
            {
                newdirpath = path + @"\mydir" + i;
                dirInfo = new DirectoryInfo(newdirpath);
                if (dirInfo.Exists)
                {
                    dirInfo.Delete();
                }
            }

            Console.ReadKey();
        }
        /// <summary>
        /// Writes index files into the specified directory.
        /// </summary>
        /// <param name="indexDirectory">The directory into which the index files should be written.</param>
        /// <param name="recordMapper">The mapper for the records.</param>
        /// <param param name="records">The records which should be written.</param>
        public void WriteDirectory(DirectoryInfo indexDirectory, IRecordMapper<string> recordMapper, IEnumerable<IReferenceRecord> records)
        {
            if (!indexDirectory.Exists)
            {
                indexDirectory.Create();
            }

            var directoryNames = new HashSet<string>();
            foreach (var directory in indexDirectory.GetDirectories())
            {
                if (!directoryNames.Contains(directory.Name))
                {
                    directoryNames.Add(directory.Name);
                }
            }
            foreach (var record in records)
            {
                var directoryName = recordMapper.Map(record);
                if (!directoryNames.Contains(directoryName))
                {
                    indexDirectory.CreateSubdirectory(directoryName);
                    directoryNames.Add(directoryName);
                }

                // Write index files into the index directory
            }
        }
        /// <summary>
        /// Creates a file to put data
        /// </summary>
        /// <param name="category">Type of data being stored. Only AlphaNumeric characters are supported.</param>
        /// <param name="name">Name or description of the data item. Does not have to be unique. Only valid file name characters are supported.</param>
        /// <param name="key">Key to identify the blob</param>
        /// <param name="file">FileInfo object</param>
        /// 
        private void CreateFile(string category, string name, out string key, out FileInfo file)
        {
            DateTime ts = DateTime.Now;
            string id = Guid.NewGuid().ToString("N");

            // Check input syntax
            if (!Regex.Match(category, "^[A-Za-z0-9]+$").Success)
            { throw new MigrationException(MigrationExceptionCodes.BLOB_STORE_PROVIDER_ERROR_CATEGORY_SYNTAX, "", category); }
            if (!Regex.Match(name, "^[A-Za-z0-9\\._-]+$").Success)
            { throw new MigrationException(MigrationExceptionCodes.BLOB_STORE_PROVIDER_ERROR_NAME_SYNTAX, "", name); }

            // Build return key
            key = string.Format("{0}:{1}:{2}:{3}", category, ts.ToString("yyyyMMddHH"), id, name);

            // Make directory where we want to save the data
            string relativePath = string.Format("{0}\\{1}\\{2}\\{3}\\{4}", category, ts.Year,
                ts.Month.ToString("00"), ts.Day.ToString("00"), ts.Hour.ToString("00"));
            DirectoryInfo dir = new DirectoryInfo(_rootPath + relativePath);
            if (!dir.Exists)
            { dir.Create(); }

            // Make the file name - if file exists, rename it
            string fileName = string.Format("{0}_{1}", id, name);
            file = new FileInfo(dir.FullName + "\\" + fileName);

        }
Esempio n. 36
0
        static void Main(string[] args)
        {
            var watchedFolder = new DirectoryInfo(WatcherFolder);
            if (!watchedFolder.Exists)
            {
                watchedFolder.Create();
            }

            Console.WriteLine("Press any key to exit");
            Console.WriteLine(string.Format("Try copying one file into watched folder ({0})", watchedFolder.FullName));
            Console.WriteLine("Try copying a batch of files into a watched folder");

            var fileWatcher = EnhancedFileSystemWatcherFactory.Instance.CreateEnhancedFileSystemWatcher(watchedFolder.FullName, "", 1000, true);
            fileWatcher.Start();

            fileWatcher.DirectoryCreatedEvent += OnFileWatcherDirectoryCreatedEvent;
            fileWatcher.DirectoryDeletedEvent += OnFileWatcherDirectoryDeletedEvent;
            fileWatcher.DirectoryRenamedEvent += OnFileWatcherDirectoryRenamedEvent;

            fileWatcher.FileCreatedEvent += OnFileCreatedEvent;
            fileWatcher.FileChangedEvent += OnFileChangedEvent;
            fileWatcher.FileFinishedChangingEvent += OnFileFinishedChangingEvent;
            fileWatcher.FileRenamedEvent += OnFileRenamedEvent;
            fileWatcher.FileDeletedEvent += OnFileDeletedEvent;
            fileWatcher.FilesFinishedChangingEvent += OnFilesFinishedChangingEvent;
            fileWatcher.FileActivityFinishedEvent += OnFileActivityFinishedEvent;

            Console.ReadKey();
            fileWatcher.Stop();
        }
Esempio n. 37
0
        /// <summary>
        /// Creates a file from a list of strings; each string is placed on a line in the file.
        /// </summary>
        /// <param name="TempFileName">Name of response file</param>
        /// <param name="Lines">List of lines to write to the response file</param>
        public static string Create(string TempFileName, List<string> Lines)
        {
            FileInfo TempFileInfo = new FileInfo( TempFileName );
            DirectoryInfo TempFolderInfo = new DirectoryInfo( TempFileInfo.DirectoryName );

            // Delete the existing file if it exists
            if( TempFileInfo.Exists )
            {
                TempFileInfo.IsReadOnly = false;
                TempFileInfo.Delete();
                TempFileInfo.Refresh();
            }

            // Create the folder if it doesn't exist
            if( !TempFolderInfo.Exists )
            {
                // Create the
                TempFolderInfo.Create();
                TempFolderInfo.Refresh();
            }

            using( FileStream Writer = TempFileInfo.OpenWrite() )
            {
                using( StreamWriter TextWriter = new StreamWriter( Writer ) )
                {
                    Lines.ForEach( x => TextWriter.WriteLine( x ) );
                }
            }

            return TempFileName;
        }
Esempio n. 38
0
		private void CreateFlags( DirectoryInfo dir )
		{
			DirectoryInfo readDir = new DirectoryInfo( Path.Combine( dir.FullName, "gfx/flags" ).Replace( '\\', '/' ) );

			string writeDirStr = Path.Combine( m_options.Data.MyDocsDir.FullName, m_options.Mod.Path );
			writeDirStr = Path.Combine( writeDirStr, "gfx/flags" ).Replace( '\\', '/' );
			DirectoryInfo writeDir = new DirectoryInfo( writeDirStr );

			if( !readDir.Exists )
				return;

			if( TaskStatus.Abort )
				return;
			if( !writeDir.Exists )
				writeDir.Create();

			CreateFlagsFromCounties( writeDir, readDir );

			if( TaskStatus.Abort )
				return;
			CreateFlagsFromDuchies( writeDir, readDir );

			if( TaskStatus.Abort )
				return;
			CreateFlagsFromKingdoms( writeDir, readDir );
		}
        public ExecuteAutomationEmailBuilder()
        {
            //Get obsolute path for logging from config file.
            string LogfileDirPath = ConfigurationManager.AppSettings["LogFileDirPath"].ToString();
            //Create one folder with today's date. Client's logfiles are stored in that folder.
            string logFileFolderName = DateTime.Now.Month.ToString().PadLeft(2, '0') + "-" +
                                        DateTime.Now.Day.ToString().PadLeft(2, '0') + "-" +
                                        DateTime.Now.Year.ToString().Substring(2, 2).PadLeft(2, '0');
            DirectoryInfo dirInfo = new DirectoryInfo(Path.Combine(LogfileDirPath, logFileFolderName));
            if (!dirInfo.Exists)
                dirInfo.Create();
            //Combine obsulute logfile path.
            logforemailbuilder = Path.Combine(Path.Combine(LogfileDirPath, logFileFolderName), "RPLOG_AUTOMATIONEMAILBUILDER.txt");

            //clientConnectionString = ConfigurationManager.ConnectionStrings["Development"].ConnectionString;

            //Use below code to connect to local drive folder.
            pickupPath = ConfigurationManager.AppSettings["LocalPickupPath"].ToString();

            //Use below code to connect to network drive shared folder.
            //pickupPath = ConfigurationManager.AppSettings["SharedPickupPath"].ToString();
            //ImpersonateUser objImpersonateUser = new ImpersonateUser();
            //objImpersonateUser.Impersonate("192.168.0.199", "administrator", "pspl.1234");

            DirectoryInfo dirlogInfo = new DirectoryInfo(pickupPath);
            if (!dirlogInfo.Exists)
                dirlogInfo.Create();
        }
Esempio n. 40
0
        public void CheckDialogSaveFolder()
        {
            string today = "";
            string month = "";
            string dialogDir = "";
            DirectoryInfo resultDirInfo = null;
            try
            {
                today = DateTime.Now.ToShortDateString();
                month = today.Substring(0, 7);
                dialogDir = string.Format(WeDoCommon.ConstDef.MSGR_DATA_DLOG_DIR, ConfigHelper.Id)
                     + month + "\\" + today;

                resultDirInfo = new DirectoryInfo(dialogDir);
                if (!resultDirInfo.Exists)
                {
                    resultDirInfo.Create();
                    Logger.info(string.Format(" 대화저장폴더[{0}] 생성", dialogDir));
                }
            }
            catch (Exception e)
            {
                Logger.error(string.Format(" 대화저장폴더[{0}] 생성 실패:", dialogDir) + e.ToString());
            };
            
        }
Esempio n. 41
0
 public void ValidDirectoryName()
 {
     string dirName = Path.Combine(TestDirectory, Path.GetRandomFileName());
     DirectoryInfo dir = new DirectoryInfo(dirName);
     dir.Create();
     Assert.Equal(dir.Name, Path.GetFileName(dirName));
 }
Esempio n. 42
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ReplEditor"/> class.
        /// </summary>
        public ReplEditor()
            : base(null)
        {
            this.Caption = "Repl Script Editor for Visual Studio - " + typeof(ReplEditor).Assembly.GetName().Version.ToString();
            //deploy sample script if needed
            var di = new DirectoryInfo(VSTools.ScriptsDirectory);
            if (!di.Exists) di.Create();

            var fileName = VSTools.DefaultScriptFileName;
            if (!File.Exists(fileName))
            {
                var assembly = Assembly.GetExecutingAssembly();
                var resourceName = "VSReplPackage.SampleScript.cs";

                using (Stream stream = assembly.GetManifestResourceStream(resourceName))
                using (StreamReader reader = new StreamReader(stream))
                {
                    string s = reader.ReadToEnd();
                    File.WriteAllText(fileName, s, Encoding.UTF8);
                }
            }
            // This is the user control hosted by the tool window; Note that, even if this class implements IDisposable,
            // we are not calling Dispose on this object. This is because ToolWindowPane calls Dispose on
            // the object returned by the Content property.
            //this.Content = new ReplEditorControl();
            //init services
        }
Esempio n. 43
0
        static void CopyDirectory(string srcDir, string tgtDir)
        {
            DirectoryInfo source = new DirectoryInfo(srcDir);
            DirectoryInfo target = new DirectoryInfo(tgtDir);

            if (target.FullName.StartsWith(source.FullName.EndsWith("\\") ? source.FullName : (source.FullName + "\\"), StringComparison.CurrentCultureIgnoreCase))
            {
                throw new Exception("父目录不能拷贝到子目录!");
            }

            if (!source.Exists)
            {
                return;
            }

            if (!target.Exists)
            {
                target.Create();
            }

            FileInfo[] files = source.GetFiles();

            for (int i = 0; i < files.Length; i++)
            {
                File.Copy(files[i].FullName, target.FullName + @"\" + files[i].Name, true);
            }

            DirectoryInfo[] dirs = source.GetDirectories();

            for (int j = 0; j < dirs.Length; j++)
            {
                CopyDirectory(dirs[j].FullName, target.FullName + @"\" + dirs[j].Name);
            }
        }
Esempio n. 44
0
 /// <summary>
 /// Checks if the directory path provided exists, and creates it if it does not.
 /// </summary>
 void CreateDirectoryIfNew(string directoryPath)
 {
     System.IO.DirectoryInfo dirInf = new System.IO.DirectoryInfo(directoryPath);
     if (!dirInf.Exists)
     {
         dirInf.Create();
     }
 }
Esempio n. 45
0
    private void CreateDirectory(System.IO.DirectoryInfo dir)
    {
        if (!dir.Parent.Exists)
        {
            this.CreateDirectory(dir.Parent);
        }

        dir.Create();
    }
Esempio n. 46
0
 public static void EnsureDirectoryExists(string dir)
 {
     System.IO.DirectoryInfo dirInfo = new System.IO.DirectoryInfo(dir);
     if (!dirInfo.Exists)
     {
         dirInfo.Create();
         Console.WriteLine("Created directory: " + dir);
     }
 }
Esempio n. 47
0
 static public int Create(IntPtr l)
 {
     try {
         System.IO.DirectoryInfo self = (System.IO.DirectoryInfo)checkSelf(l);
         self.Create();
         pushValue(l, true);
         return(1);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
    void Awake()
    {
        if (NewSceneManager.SceneIndex != 0)
        {
            Debug.LogError("Game must be started from sInit scene!");
#if UNITY_EDITOR
            UnityEditor.EditorApplication.isPlaying = false;
#endif
            Application.Quit();
        }

        // Typical singleton
        if (_instance == null)
        {
            _instance = this;
        }
        else
        {
            Destroy(gameObject);
            return;
        }

        // Create black transition shader at runtime
        // For the actual source of this see https://answers.unity.com/answers/119951/view.html
#if UNITY_EDITOR
        var resDir = new System.IO.DirectoryInfo(System.IO.Path.Combine(Application.dataPath, "Resources"));
        if (!resDir.Exists)
        {
            resDir.Create();
        }
        Shader s = Shader.Find("Plane/No zTest");
        if (s == null)
        {
            string shaderText = "Shader \"Plane/No zTest\" { SubShader { Pass { Blend SrcAlpha OneMinusSrcAlpha ZWrite Off Cull Off Fog { Mode Off } BindChannels { Bind \"Color\",color } } } }";
            string path       = System.IO.Path.Combine(resDir.FullName, "Plane_No_zTest.shader");
            System.IO.File.WriteAllText(path, shaderText);
            UnityEditor.AssetDatabase.Refresh(UnityEditor.ImportAssetOptions.ForceSynchronousImport);
            UnityEditor.AssetDatabase.LoadAssetAtPath <Shader>("Resources/Plane_No_zTest.shader");
            s = Shader.Find("Plane/No zTest");
        }
        Material mat = new Material(s);
        mat.name = "Plane_No_zTest";
        UnityEditor.AssetDatabase.CreateAsset(mat, "Assets/Resources/Plane_No_zTest.mat");
#endif

        soundManager = transform.GetChild(0).GetComponent <SoundManager>();

        DontDestroyOnLoad(this);

        SaveLoadManager.LoadGame();
    }
Esempio n. 49
0
 static public int Create__DirectorySecurity(IntPtr l)
 {
     try {
         System.IO.DirectoryInfo self = (System.IO.DirectoryInfo)checkSelf(l);
         System.Security.AccessControl.DirectorySecurity a1;
         checkType(l, 2, out a1);
         self.Create(a1);
         pushValue(l, true);
         return(1);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Esempio n. 50
0
    // Use this for initialization

    /*void Start()
     * {
     *  Debug.Log(System.DateTime.Now.ToString("yyyyMMddHHmmss"));
     *  Debug.Log(Application.dataPath.Replace('/', '\\'));
     * }*/

    // Update is called once per frame

    /*void Update()
     * {
     *  if (Input.GetKeyDown(KeyCode.End)) Save(1);
     *  if (Input.GetKeyDown(KeyCode.Home)) Load(1);
     * }*/


    public void Save(int index)
    {
        CloseUI();
        try
        {
            string date   = System.DateTime.Now.ToString("yyyyMMddHHmmss");
            string folder = string.Empty;
            switch (index)
            {
            case 1: folder = folder1; break;

            case 2: folder = folder2; break;

            case 3: folder = folder3; break;

            default: folder = autoSaveFolder; break;
            }
            if (!System.IO.Directory.Exists(Application.persistentDataPath + folder))
            {
                System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(Application.persistentDataPath + folder);
                di.Create();
            }
            PlayerInfoManager.Instance.SavePlayerInfo(Application.persistentDataPath + folder, globalKey, true);
            PlayerSkillManager.Instance.SaveToFile(Application.persistentDataPath + folder, globalKey, true);
            ShopManager.Instance.SaveToFile(Application.persistentDataPath + folder, globalKey, true);
            TalkManager.Instance.Save(Application.persistentDataPath + folder, globalKey, true);
            string[] datas =
            {
                date,
                PlayerInfoManager.Instance.PlayerInfo.Level.ToString(),
                PlayerInfoManager.Instance.PlayerInfo.characterInfo.Name,
                Encryption.Encrypt(PlayerInfoManager.Instance.PlayerInfo.ID.ToString(),                                     globalKey),
                Encryption.Encrypt(TimeLineManager.Instance.currentTime.ToString(),                                         globalKey),
                Encryption.Encrypt(Newtonsoft.Json.JsonConvert.SerializeObject(SelectClosestSavePoint().transform.position),globalKey),
                Encryption.Encrypt(MyTools.GetMD5(Application.persistentDataPath + folder + PlayerInfoManager.DataName),    globalKey),
                Encryption.Encrypt(MyTools.GetMD5(Application.persistentDataPath + folder + BagInfo.DataName),              globalKey),
                Encryption.Encrypt(MyTools.GetMD5(Application.persistentDataPath + folder + WarehouseInfo.DataName),        globalKey),
                Encryption.Encrypt(MyTools.GetMD5(Application.persistentDataPath + folder + PlayerSkillManager.DataName1),  globalKey),
                Encryption.Encrypt(MyTools.GetMD5(Application.persistentDataPath + folder + PlayerSkillManager.DataName2),  globalKey),
                Encryption.Encrypt(MyTools.GetMD5(Application.persistentDataPath + folder + ShopManager.DataName),          globalKey),
                Encryption.Encrypt(MyTools.GetMD5(Application.persistentDataPath + folder + TalkManager.DataName),          globalKey)
            };
            System.IO.File.WriteAllLines(Application.persistentDataPath + folder + "/Data", datas, System.Text.Encoding.UTF8);
        }
        catch (System.Exception ex)
        {
            Debug.LogWarning(ex.Message);
        }
    }
Esempio n. 51
0
    // Use this for initialization
    void Start()
    {
        Screen.SetResolution(400, 600, false);

        SavePath = Application.persistentDataPath + "/CustomMaps/";
        dirCheck = new System.IO.DirectoryInfo(SavePath);
        if (dirCheck.Exists == false)
        {
            dirCheck.Create();
        }

        filename = new StringBuilder();
        filename.Append(SavePath);
        Debug.Log(filename);
    }
Esempio n. 52
0
    void OnEnable()
    {
#if !UNITY_EDITOR
        // If the xml configuration file does not exists, create it
        if (!ReadXml(xmlConfigFolder + @"LensEncoder.xml"))
        {
            System.IO.DirectoryInfo sensorDir = new System.IO.DirectoryInfo(xmlConfigFolder);
            if (!sensorDir.Exists)
            {
                sensorDir.Create();
            }
            WriteXml(xmlConfigFolder + @"LensEncoder.xml");
        }
#endif
        enabled = Connect();
    }
Esempio n. 53
0
    /// <summary>
    /// Create a folder at the specified path.
    /// </summary>
    /// <param name="dInfo"></param>
    /// <returns></returns>
    public static bool CreateFolder(System.IO.DirectoryInfo dInfo)
    {
        // TODO: Create parent directories if they don't exist
        bool folderCreated = false;

        if (dInfo != null)
        {
            if (!dInfo.Exists)
            {
                dInfo.Create();
                dInfo.Refresh();
                folderCreated = dInfo.Exists;
                Console.WriteLine(folderCreated ? "INFO: Util: Creating folder: " : "INFO: Util: Failed to create folder: " + dInfo.FullName);
            }
        }
        return(folderCreated);
    }
Esempio n. 54
0
    static void Main(string[] args)
    {
        if (args.Length == 0)
        {
            Console.WriteLine("You must pass in a arugment of Y or N ");
        }

        mc = new Microsoft.VisualBasic.Devices.Computer();

        string strData = "";

        strData += "PC Information" + "\r\n";
        strData += GetPCInfo() + "\r\n";
        strData += "Drive Information" + "\r\n";
        strData += GetDriveInfo() + "\r\n";
        strData += "Memory Information" + "\r\n";
        strData += GetMemoryInfo() + "\r\n";
        try
        {
            if (args[0] == "y")
            {
                System.IO.DirectoryInfo DI = new System.IO.DirectoryInfo("c:\\PCInfo");
                if (!(DI.Exists))
                {
                    DI.Create();
                }
                WriteReport(strData);
            }
            else if (args[0] == "n")
            {
                Console.WriteLine(strData);
            }
            else
            {
                Console.WriteLine("You must chose to write to file or not.");
                Console.WriteLine("y or n after the program name");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }
Esempio n. 55
0
    private static void ExtractJSLib()
    {
        var path   = System.IO.Path.Combine(Application.dataPath, "Plugins");
        var folder = new System.IO.DirectoryInfo(path);

        if (!folder.Exists)
        {
            folder.Create();
        }
        path = System.IO.Path.Combine(path, "URLParameters.jslib");
        if (System.IO.File.Exists(path))
        {
            return;
        }
        Debug.Log("URLParameters.jslib does not exist in the plugins folder, extracting");
        System.IO.File.WriteAllText(path, m_EmbeddedLib);
        UnityEditor.AssetDatabase.Refresh();
        UnityEditor.EditorApplication.RepaintProjectWindow();
    }
Esempio n. 56
0
    protected string UploadToDocumentFolder()
    {
        string strTmpFolder = HROne.Common.Folder.GetOrCreateSessionTempFolder(Session.SessionID).FullName;// System.IO.Path.GetTempPath(); //Environment.GetFolderPath(Environment.SpecialFolder.InternetCache);
        string strTmpFile   = System.IO.Path.Combine(strTmpFolder, AppUtils.ServerDateTime().ToString("~yyyyMMddHHmmss_") + Server.UrlEncode(UploadDocumentFile.FileName));

        UploadDocumentFile.SaveAs(strTmpFile);

        string relativePath    = System.IO.Path.Combine(dbConn.Connection.Database, CurEmpID + "_" + AppUtils.ServerDateTime().ToString("yyyyMMddHHmmss") + ".hrd");
        string destinationFile = System.IO.Path.Combine(uploadFolder, relativePath);

        System.IO.DirectoryInfo documentDirectoryInfo = new System.IO.DirectoryInfo(System.IO.Path.GetDirectoryName(destinationFile));
        if (!documentDirectoryInfo.Exists)
        {
            documentDirectoryInfo.Create();
        }

        zip.Compress(strTmpFolder, System.IO.Path.GetFileName(strTmpFile), destinationFile);
        System.IO.File.Delete(strTmpFile);
        return(relativePath);
    }
Esempio n. 57
0
        /// <summary>
        /// 保存访问日志
        /// </summary>
        /// <param name="_type">1代表访问者,2代表非法</param>
        /// <param name="_second">脚本秒数</param>
        /// <param name="_logfilename">自定义log保存路径</param>
        public void SaveVisitLog(int _type, int _second, string _logfilename)
        {
            System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(this.Server.MapPath("~/data_log/"));
            if (!dir.Exists)
            {
                dir.Create();
            }

            if (_type == 1)
            {
                string _savefile = _logfilename == "" ? "~/data_log/vister_" + DateTime.Now.ToString("yyyyMMdd") + ".log" : _logfilename;
                Single s         = (Single)DateTime.Now.Subtract(HttpContext.Current.Timestamp).TotalSeconds;
                if (s > _second)
                {
                    System.IO.StreamWriter sw = new System.IO.StreamWriter(HttpContext.Current.Server.MapPath(_savefile), true, System.Text.Encoding.UTF8);
                    sw.WriteLine(System.DateTime.Now.ToString());
                    sw.WriteLine("\tIP 地 址:" + GetUserIp);
                    sw.WriteLine("\t访 问 者:" + ThisUser());
                    sw.WriteLine("\t浏 览 器:" + HttpContext.Current.Request.Browser.Browser + HttpContext.Current.Request.Browser.Version);
                    sw.WriteLine("\t耗    时:" + ((Single)DateTime.Now.Subtract(HttpContext.Current.Timestamp).TotalSeconds).ToString("0.000") + "秒");
                    sw.WriteLine("\t地    址:" + ServerUrl() + GetCurrentUrl);
                    sw.WriteLine("---------------------------------------------------------------------------------------------------");
                    sw.Close();
                    sw.Dispose();
                }
            }
            else
            {
                string _savefile          = _logfilename == "" ? "~/data_log/hacker_" + DateTime.Now.ToString("yyyyMMdd") + ".log" : _logfilename;
                System.IO.StreamWriter sw = new System.IO.StreamWriter(HttpContext.Current.Server.MapPath(_savefile), true, System.Text.Encoding.UTF8);
                sw.WriteLine(System.DateTime.Now.ToString());
                sw.WriteLine("\tIP 地 址:" + GetUserIp);
                sw.WriteLine("\t访 问 者:" + ThisUser());
                sw.WriteLine("\t浏 览 器:" + HttpContext.Current.Request.Browser.Browser + HttpContext.Current.Request.Browser.Version);
                sw.WriteLine("\t来    源:" + ServerUrl() + GetCurrentUrl);
                sw.WriteLine("\t地    址:" + ServerUrl() + GetCurrentUrl);
                sw.WriteLine("---------------------------------------------------------------------------------------------------");
                sw.Close();
                sw.Dispose();
            }
        }
Esempio n. 58
0
 public static int GetNumberButtons()
 {
     if (TMPBUTTONNUMBER == 0)
     {
         System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(runPath + BUTTONFOLDER + "\\");
         try
         {
             TMPBUTTONNUMBER = dir.GetFiles().Length;
             return(dir.GetFiles().Length);
         }
         catch
         {
             dir.Create();
             return(0);
         }
     }
     else
     {
         return(TMPBUTTONNUMBER);
     }
 }
Esempio n. 59
0
File: B1_UI.cs Progetto: Fun33/code
    ///<summary>
    ///處理例外錯誤。
    ///     </summary>
    ///<param name="StartupPath">儲存的目錄位置</param>
    ///<param name="ErrorMsg">錯誤訊息</param>
    public void DealError(string StartupPath, string ErrorMsg)
    {
        string FileName = DateTime.Now.ToString("yyyyMMdd");
        string sPath    = null;

        sPath = StartupPath;

        System.IO.DirectoryInfo oDir = new System.IO.DirectoryInfo(sPath);
        if (!oDir.Exists)
        {
            oDir.Create();
        }

        System.IO.StreamWriter sw = new System.IO.StreamWriter(sPath + "\\\\" + FileName + "-Log.txt", true, System.Text.Encoding.GetEncoding("Big5"));

        sw.WriteLine(DateTime.Now.ToString() + " -------------------");
        sw.WriteLine("AddOn Path:" + System.Windows.Forms.Application.ExecutablePath);
        sw.WriteLine(ErrorMsg);
        sw.WriteLine("The End -------------------");
        sw.Close();
    }
Esempio n. 60
0
        private void picBox_Save_Click_Click(object sender, EventArgs e)
        {
            System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(Application.StartupPath + @"\Data");
            if (!di.Exists)
            {
                di.Create();
            }
            string fileName = di.ToString() + "\\COVID.txt";

            StreamWriter sw   = new StreamWriter(fileName, true);
            string       buff = "";

            //string buff = dgv_TestInfo.Rows[0].Cells[0].Value.ToString() + "," + dgv_TestInfo.Rows[0].Cells[1].Value.ToString() + ",";
            //+ dgv_tester_info.Rows[0].Cells[0].Value.ToString() + "," + dgv_tester_info.Rows[0].Cells[1].Value.ToString() + ","
            //+ dgv_cartridge_info.Rows[0].Cells[0].Value.ToString() + "," + dgv_cartridge_info.Rows[0].Cells[1].Value.ToString() + ","
            //+ dgv_cartridge_info.Rows[0].Cells[2].Value.ToString()
            //;
            sw.WriteLine(buff);

            sw.Close();
        }