• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# FileInfo类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中FileInfo的典型用法代码示例。如果您正苦于以下问题:C# FileInfo类的具体用法?C# FileInfo怎么用?C# FileInfo使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



FileInfo类属于命名空间,在下文中一共展示了FileInfo类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: LoadExcel

 public static Excel LoadExcel(string path)
 {
     FileInfo file = new FileInfo(path);
     ExcelPackage ep = new ExcelPackage(file);
     Excel xls = new Excel(ep.Workbook);
     return xls;
 }
开发者ID:joexi,项目名称:Excel4Unity,代码行数:7,代码来源:ExcelHelper.cs


示例2: GetDirectoryPath

    // Ex: C:\Users\Public\Test\blah.txt would return C:\Users\Public\Test\
    public static string GetDirectoryPath(string filePath)
    {
        if(string.IsNullOrEmpty(filePath)) return "";

        FileInfo fileInfo = new FileInfo(filePath);
        return (fileInfo != null) ? fileInfo.Directory.FullName : "";
    }
开发者ID:rowenar11,项目名称:digiforge,代码行数:8,代码来源:SaveLoadManager.cs


示例3: FalseForDirectory

 public void FalseForDirectory()
 {
     string fileName = GetTestFilePath();
     Directory.CreateDirectory(fileName);
     FileInfo di = new FileInfo(fileName);
     Assert.False(di.Exists);
 }
开发者ID:shiftkey-tester,项目名称:corefx,代码行数:7,代码来源:Exists.cs


示例4: CopyFile

	static void CopyFile(string filename, string outputfilename, string pathToBuiltProject) {
		string strCWD = Directory.GetCurrentDirectory();
		string strSource = Path.Combine(Path.Combine(strCWD, SteamAPIRelativeLoc), filename);
		string strFileDest = Path.Combine(Path.GetDirectoryName(pathToBuiltProject), outputfilename);

		if (!File.Exists(strSource)) {
			Debug.LogWarning(string.Format("[Steamworks.NET] Could not copy {0} into the project root. {0} could not be found in '{1}'. Place {0} from the redist into the project root manually.", filename, SteamAPIRelativeLoc));
			return;
		}

		if (File.Exists(strFileDest)) {
			if (File.GetLastWriteTime(strSource) == File.GetLastWriteTime(strFileDest)) {
				FileInfo fInfo = new FileInfo(strSource);
				FileInfo fInfo2 = new FileInfo(strFileDest);
				if (fInfo.Length == fInfo2.Length) {
					return;
				}
			}
		}

		File.Copy(strSource, strFileDest, true);

		if (!File.Exists(strFileDest)) {
			Debug.LogWarning(string.Format("[Steamworks.NET] Could not copy {0} into the built project. File.Copy() Failed. Place {0} from the redist folder into the output dir manually.", filename));
		}
	}
开发者ID:joeju,项目名称:Steamworks.NET,代码行数:26,代码来源:RedistCopy.cs


示例5: Parse

		public static Package Parse(FileInfo assemblyInfoFile)
		{
			try
			{
				var lines = Storage.ReadAllLines(assemblyInfoFile.FullName);

				var title = AssemblyInfo.GetData(lines, AssemblyInfoData.AssemblyTitle);

				var projectFile = assemblyInfoFile.Directory.Parent.GetFiles(title + "*.csproj").SingleOrDefault();

				if (projectFile == null)
				{
					return null;
				}

				var targetFramework = ExtractTargetFramework(projectFile);

				var version = AssemblyInfo.GetData(lines, AssemblyInfoData.AssemblyVersion);

				var nuspec = projectFile.Directory.GetFiles("Package.nuspec").SingleOrDefault();

				if (nuspec == null)
				{
					return new Package(projectFile, assemblyInfoFile, lines, title, version, targetFramework);
				}

				return new Package(projectFile, assemblyInfoFile, lines, title, version, targetFramework, nuspec);
			}
			catch (Exception exception)
			{
				throw new IOException($"Cannot parse the file {assemblyInfoFile.FullName}.", exception);
			}
		}
开发者ID:matteomigliore,项目名称:HSDK,代码行数:33,代码来源:Packages.cs


示例6: Create

    // ------------------------------------------------------------------
    // Desc:
    // ------------------------------------------------------------------
    public static exTimebasedCurveInfo Create( string _path, string _name )
    {
        //
        if ( new DirectoryInfo(_path).Exists == false ) {
            Debug.LogError ( "can't create asset, path not found" );
            return null;
        }
        if ( string.IsNullOrEmpty(_name) ) {
            Debug.LogError ( "can't create asset, the name is empty" );
            return null;
        }
        string assetPath = Path.Combine( _path, _name + ".asset" );

        // check if create the asset
        FileInfo fileInfo = new FileInfo(assetPath);
        if ( fileInfo.Exists ) {
            if ( EditorUtility.DisplayDialog( _name + " already exists.",
                                              "Do you want to overwrite the old one?",
                                              "Yes",
                                              "No" ) == false )
            {
                return null;
            }
        }

        //
        exTimebasedCurveInfo newCurve = ScriptableObject.CreateInstance<exTimebasedCurveInfo>();
        AssetDatabase.CreateAsset(newCurve, assetPath);
        Selection.activeObject = newCurve;

        return newCurve;
    }
开发者ID:exdev,项目名称:band-of-warriors,代码行数:35,代码来源:exTimebasedCurveUtility.cs


示例7: Start

    void Start()
    {
        triviaFile = new FileInfo(Application.dataPath + "/trivia.txt");

        if (triviaFile != null && triviaFile.Exists) {
            reader = triviaFile.OpenText();
        } else {
            embedded = (TextAsset) Resources.Load("trivia_embedded", typeof (TextAsset));
            reader = new StringReader(embedded.text);
        }

        string lineOfText = "";
        int lineNumber = 0;

        while ( ( lineOfText = reader.ReadLine() ) != null ) {

            string question = lineOfText;
            int answerCount = Convert.ToInt32(reader.ReadLine());
            List<string> answers = new List<string>();
            for (int i = 0; i < answerCount; i++) {
                answers.Add(reader.ReadLine());
            }

            Trivia temp = new Trivia(question, answerCount, answers);

            triviaQuestions.Add(temp);
            lineNumber++;
        }

        SendMessage( "BeginGame" );
    }
开发者ID:LivingValkyrie,项目名称:Lab04,代码行数:31,代码来源:TriviaLoader.cs


示例8: IsFileLocked

    protected static bool IsFileLocked(string fullPath)
    {
        FileInfo file = new FileInfo(fullPath);

        FileStream stream = null;

        try
        {
            stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
        }
        catch (IOException)
        {
            //the file is unavailable because it is:
            //still being written to
            //or being processed by another thread
            //or does not exist (has already been processed)
            return true;
        }
        finally
        {
            if (stream != null)
                stream.Close();
        }

        //file is not locked
        return false;
    }
开发者ID:fjkish,项目名称:DotNet,代码行数:27,代码来源:Program.cs


示例9: Slice

    static void Slice(string sourceFile, string destinationDirectory, int parts)
    {
        string extension = new FileInfo(sourceFile).Extension;
        ext = extension;

        using (var source = new FileStream(destinationDirectory + sourceFile, FileMode.Open))
        {
            int pieceSize = (int)Math.Ceiling((decimal)source.Length / parts);
            byte[] buffer = new byte[4096];

            for (int i = 1; i <= parts; i++)
            {

                string currentFilePath = string.Format(destinationDirectory + "part" + i + extension);
                using (var destination =
                    new FileStream(currentFilePath, FileMode.Create))
                {

                    long partBytes = 0;
                    while (partBytes < pieceSize)
                    {
                        int readBytes = source.Read(buffer, 0, buffer.Length);
                        if (readBytes == 0)
                        {
                            break;;
                        }
                        destination.Write(buffer, 0, readBytes);
                        partBytes += readBytes;
                    }
                }
                slicedFiles.Add(currentFilePath);
            }
        }
    }
开发者ID:BiserVStoev,项目名称:SoftUni-CSharp-Advanced,代码行数:34,代码来源:SlicingFile.cs


示例10: StartProcess

    /// <summary>
    /// プロセスを実行
    /// </summary>
    public void StartProcess(ProcessData procData)
    {
        if(procData.use && !procData.IsRunning)
        {
            FileInfo fileInfo = new FileInfo(procData.exePath);
            if(fileInfo.Exists)
            {
                Process proc = new Process();
                proc.StartInfo.FileName = Path.GetFullPath(procData.exePath);

                //引数設定
                if(procData.argument != "")
                    proc.StartInfo.Arguments = procData.argument;

                //ウィンドウスタイル設定
                if(!ApplicationSetting.Instance.GetBool("IsDebug"))
                    proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;

                try
                {
                    proc.Start();

                    processList.Add(proc);
                    procData.IsRunning = true;
                }
                catch(Exception e)
                {
                    UnityEngine.Debug.Log("ExternalProcess :: process start error - " + e.Message);
                }
            }
        }
    }
开发者ID:sgyli7,项目名称:GarageKit_for_Unity,代码行数:35,代码来源:ExternalProcess.cs


示例11: WithNoWeaving

    public void WithNoWeaving()
    {
        var sourceProjectFile = new FileInfo(@"TestProjects\ProjectWithNoWeaving.csproj");
        var targetFileInfo = sourceProjectFile.CopyTo(sourceProjectFile.FullName + "ProjectReaderTest", true);
        try
        {

            var reader = new ProjectReader(targetFileInfo.FullName);

            Assert.IsNull(reader.DependenciesDirectory);
            Assert.IsNull(reader.ToolsDirectory);
            Assert.IsNull(reader.CheckForEquality);
            Assert.IsNull(reader.CheckForIsChanged);
            Assert.IsNull(reader.ProcessFields);
            Assert.IsNull(reader.MessageImportance);
            Assert.IsNull(reader.TryToWeaveAllTypes);
            Assert.IsNull(reader.EventInvokerName);
            Assert.IsNull(reader.EventInvokerName);
            Assert.IsNull(reader.TargetPath);
            Assert.IsNull(reader.TargetNode);
            Assert.IsNull(reader.DependenciesDirectory);
        }
        finally
        {
            targetFileInfo.Delete();
        }
    }
开发者ID:Z731,项目名称:NotifyPropertyWeaver,代码行数:27,代码来源:ProjectReaderTests.cs


示例12: Start

    // Use this for initialization
    void Start()
    {
        FileStream file = null;
        FileInfo fileInfo = null;

        try
        {
            fileInfo = new FileInfo("file.txt");
            file = fileInfo.OpenWrite();

            for(int i = 0; i < 255; i++)
            {
                file.WriteByte((byte)i);
            }

            throw new ArgumentNullException("Something bad happened.");
        }
        catch(UnauthorizedAccessException e)
        {
            Debug.LogWarning(e.Message);
        }

        catch (ArgumentNullException e)
        {
            //Debug.LogWarning(e.Message);
            Debug.LogWarning("BAD!!!");
        }
        finally
        {
            if (file != null)
                file.Close();
        }
    }
开发者ID:MagicManiacs,项目名称:The_Balance_of_Magic,代码行数:34,代码来源:ExceptionTester.cs


示例13: EvaluateRelativePath

    /// <summary>
    /// Evaluates and provides the relative path.
    /// </summary>
    /// <param name="mainDirPath">The source, or starting location.</param>
    /// <param name="absoluteFilePath">The location to find.</param>
    /// <returns></returns>
    public static string EvaluateRelativePath(this FileInfo mainDirPath, FileInfo absoluteFilePath)
    {
        string[] firstPathParts = mainDirPath.FullName.Trim(Path.DirectorySeparatorChar).Split(Path.DirectorySeparatorChar);
        string[] secondPathParts = absoluteFilePath.FullName.Trim(Path.DirectorySeparatorChar).Split(Path.DirectorySeparatorChar);

        int sameCounter = 0;
        for (int i = 0; i < Math.Min(firstPathParts.Length, secondPathParts.Length); i++)
        {
          if (!firstPathParts[i].ToLower().Equals(secondPathParts[i].ToLower()))
        break;

          sameCounter++;
        }

        if (sameCounter == 0)
          return absoluteFilePath.FullName;

        string newPath = String.Empty;
        for (int i = sameCounter; i < firstPathParts.Length; i++)
        {
          if (i > sameCounter)
        newPath += Path.DirectorySeparatorChar;

          newPath += "..";
        }

        for (int i = sameCounter; i < secondPathParts.Length; i++)
        {
          newPath = String.Format("{0}{1}{2}", newPath, Path.DirectorySeparatorChar, secondPathParts[i]);
        }

        return newPath;
    }
开发者ID:mnoreke,项目名称:MNorekePublic,代码行数:39,代码来源:FileInfoExtensions.cs


示例14: FindLargeFiles

	public void FindLargeFiles(List<string> AllowedExtensions, long MinSize)
	{
		foreach (string Filename in Manifest)
		{
			FileInfo FI = new FileInfo(Filename);
			long Size = FI.Length;

			if (Size > MinSize)
			{
				bool bAllowed = false;
				foreach (string Extension in AllowedExtensions)
				{
					if (Filename.EndsWith(Extension, StringComparison.InvariantCultureIgnoreCase))
					{
						bAllowed = true;
						break;
					}
				}

				if (!bAllowed)
				{
					CommandUtils.LogWarning("{0} is {1} with an unexpected extension", Filename, AnalyzeThirdPartyLibs.ToMegabytes(Size));
				}
			}
		}
	}
开发者ID:zhaoyizheng0930,项目名称:UnrealEngine,代码行数:26,代码来源:AnalyzeThirdPartyLibs.Automation.cs


示例15: Start

        public object Start(string level)
        {
            LocalNode node = new LocalNode(Assembly.GetExecutingAssembly());
            node.Join();

            try
            {
                FileInfo levelInfo = new FileInfo(level);
                if (levelInfo.Directory.Name != "Resources")
                    return "Level is not in a resources directory.";

                DirectoryInfo directoryInfo = levelInfo.Directory.Parent;
                World.BaseDirectory = directoryInfo.FullName;
                World.RuntimeDirectory = new FileInfo(Assembly.GetExecutingAssembly().Location).Directory.FullName;

                using (RuntimeGame game = new RuntimeGame(levelInfo.Name.Substring(0, levelInfo.Name.Length - levelInfo.Extension.Length)))
                {
                    game.Run();
                }
            }
            finally
            {
                node.Leave();
            }

            return null;
        }
开发者ID:EgoIncarnate,项目名称:Tychaia,代码行数:27,代码来源:OgmoRunner.cs


示例16: SelectTextFile

 public void SelectTextFile(string file)
 {
     if (file == "FirstScene") {
         fileName = file;
         theSourceFile = new FileInfo ("Assets/Scripts/Dialogue/FirstScene.txt");
         reader = theSourceFile.OpenText ();
         startText = true;
     } else if (file == "Level1End") {
         fileName = file;
         theSourceFile = new FileInfo ("Assets/Scripts/Dialogue/Level1End.txt");
         reader = theSourceFile.OpenText ();
         startText = true;
     } else if (file == "GoodEnding") {
         fileName = file;
         theSourceFile = new FileInfo ("Assets/Scripts/Dialogue/FinalDialogues/GoodEnding.txt");
         reader = theSourceFile.OpenText ();
         startText = true;
     } else if (file == "BadEnding") {
         fileName = file;
         theSourceFile = new FileInfo ("Assets/Scripts/Dialogue/FinalDialogues/BadEnding.txt");
         reader = theSourceFile.OpenText ();
         startText = true;
     } else {
         theSourceFile = null;
     }
 }
开发者ID:Archimedyz,项目名称:COMP_376_Project,代码行数:26,代码来源:Dialogue.cs


示例17: SaveAs

 /// <summary>
 ///     A string extension method that save the string into a file.
 /// </summary>
 /// <param name="this">The @this to act on.</param>
 /// <param name="file">The FileInfo.</param>
 /// <param name="append">(Optional) if the text should be appended to file file if it's exists.</param>
 public static void SaveAs(this string @this, FileInfo file, bool append = false)
 {
     using (TextWriter tw = new StreamWriter(file.FullName, append))
     {
         tw.Write(@this);
     }
 }
开发者ID:fqybzhangji,项目名称:Z.ExtensionMethods,代码行数:13,代码来源:String.SaveAs.cs


示例18: btn_download_Click

    protected void btn_download_Click(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();
        dt.TableName = "All_Contacts";
        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dlgf"].ConnectionString))
        {
            SqlCommand cmd = new SqlCommand("[CTX].[sp_Select_All_List]", conn);
            conn.Open();
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            adapter.Fill(dt);
            conn.Close();
        }

        string dir = Server.MapPath("All_List_output");
        string milli = DateTime.Now.Millisecond.ToString();
        FileInfo newFile = new FileInfo(dir + @"\CTX_"+ milli + ".xlsx");
        if (newFile.Exists)
        {
            newFile.Delete();  // ensures we create a new workbook
            newFile = new FileInfo(dir + @"\CTX_" + milli + ".xlsx");
        }

        using (ExcelPackage pack = new ExcelPackage(newFile))
        {
            ExcelWorksheet ws = pack.Workbook.Worksheets.Add(dt.TableName.ToString());
            ws.Cells["A1"].LoadFromDataTable(dt, true);
            pack.Save();
        }

        string path = dir + @"\" + newFile.Name;
        Response.ContentType = "application/excel";
        Response.AppendHeader("Content-Disposition", "attachment; filename=\"" + newFile.Name + "\""); //file name must be in double quotes to allow spaces in the filename
        Response.TransmitFile(path);
        Response.End();
    }
开发者ID:243,项目名称:ConTAX,代码行数:35,代码来源:AllContacts.aspx.cs


示例19: renameFile

 public static void renameFile(DirectoryInfo directory, FileInfo[] files, int i, string nameNumber)
 {
     Console.WriteLine(directory.Name);
     string newName = [email protected]"\"+directory.Name + "-" + nameNumber+((FileInfo)files[i]).Extension;
     Console.WriteLine(newName);
     File.Move(((FileInfo)files[i]).FullName, newName);
 }
开发者ID:JonathanGiovanny,项目名称:codingground,代码行数:7,代码来源:main.cs


示例20: Returned304

    /// <summary>
    /// Returns 304 (use cached version) code to the client if
    /// file was not changed since last request.
    /// </summary>
    /// <param name="fileInfo">File location information</param>
    /// <returns>True if 304 was returned.</returns>
    public static bool Returned304(FileInfo fileInfo)
    {
        if (!fileInfo.Exists)
            return false;

        return Returned304(fileInfo.LastWriteTime);
    }
开发者ID:Dashboard-X,项目名称:MP3-MusicPlayer-Install-Configure,代码行数:13,代码来源:UtilityMethods.cs



注:本文中的FileInfo类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# FileLineRecorderContext类代码示例发布时间:2022-05-24
下一篇:
C# FileIOPermissionAccess类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap