当前位置: 首页>>代码示例>>C#>>正文


C# FileInfo.Substring方法代码示例

本文整理汇总了C#中System.IO.FileInfo.Substring方法的典型用法代码示例。如果您正苦于以下问题:C# FileInfo.Substring方法的具体用法?C# FileInfo.Substring怎么用?C# FileInfo.Substring使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.IO.FileInfo的用法示例。


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

示例1: MakeRelative

        public static String MakeRelative(String path, String fromPath)
        {
            List<String> pathComponents = new List<String>();

            if (fromPath == null)
            {
                return path;
            }

            /* Use FileSystemInfo to canonicalize paths, ensure fromPath ends in a trailing \ to fromPath. */
            path = new FileInfo(path).FullName;
            fromPath = new FileInfo(fromPath + @"\").FullName;

            if (fromPath.Equals(new FileInfo(path + @"\").FullName))
            {
                return ".";
            }

            /* Find the longest common base directory */
            String baseDirectory = null;

            for (int i = 0, lastSeparatorIdx = -1; ; i++)
            {
                if (i == path.Length || i == fromPath.Length || path[i] != fromPath[i])
                {
                    baseDirectory = (lastSeparatorIdx >= 0) ? path.Substring(0, lastSeparatorIdx + 1) : null;
                    break;
                }
                else if (path[i] == Path.DirectorySeparatorChar)
                {
                    lastSeparatorIdx = i;
                }
            }

            /* No common directories (on different drives), no relativization possible */
            if (baseDirectory == null)
            {
                return path;
            }

            /* Find the distance from the relativeFromPath to the baseDirectory */
            String fromRelativeToBase = fromPath.Substring(baseDirectory.Length);
            for (int i = 0; i < fromRelativeToBase.Length; i++)
            {
                if (fromRelativeToBase[i] == Path.DirectorySeparatorChar)
                {
                    pathComponents.Add("..");
                }
            }

            /* Add the path portion relative to the base */
            pathComponents.Add(path.Substring(baseDirectory.Length));

            return String.Join(new String(new char[] { Path.DirectorySeparatorChar }), pathComponents.ToArray());
        }
开发者ID:jrbriggs,项目名称:gitpowershell,代码行数:55,代码来源:FileSystemUtil.cs

示例2: Main

        static void Main( string[] args )
        {
            var outputDirPath = System.IO.Path.Combine( Application.StartupPath, "Output" );
            if( !Directory.Exists( outputDirPath ) )
            {
                try
                {
                    Directory.CreateDirectory( outputDirPath );
                }
                catch( Exception ex )
                {
                    Console.WriteLine( ex.Message );
                    Console.ReadKey();
                    return;
                }
            }
            foreach( var fn in Directory.GetFiles( Application.StartupPath, "PacketTemplate_*.dll" ) )
            {
                var asm = Assembly.LoadFile( fn );
                var t = Helpers.GetTemplate( asm );
                var shortfn = new FileInfo( fn ).Name;
                shortfn = shortfn.Substring( 0, shortfn.LastIndexOf( '.' ) );
                var path = System.IO.Path.Combine( outputDirPath, shortfn.Replace( ".", "_" ) );
                if( !Directory.Exists( path ) )
                {
                    try
                    {
                        Directory.CreateDirectory( path );
                    }
                    catch( Exception ex )
                    {
                        Console.WriteLine( ex.Message );
                        Console.ReadKey();
                        return;
                    }
                }

                var rtv = GenCPP.Gen( t, path, shortfn.Substring( "PacketTemplate_".Length ) );
                if( rtv != "" )
                {
                    Console.WriteLine( rtv );
                    Console.ReadKey();
                    return;
                }
            }
        }
开发者ID:whuthj,项目名称:69net,代码行数:46,代码来源:Program.cs

示例3: Gen

        public static void Gen()
        {
            var outputDirPath = @"..\Json";//System.IO.Path.Combine( Application.StartupPath, "Output" );
            if (!Directory.Exists(outputDirPath))
            {
                try
                {
                    Directory.CreateDirectory(outputDirPath);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Console.ReadKey();
                    return;
                }
            }
            foreach (var fn in Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "T_*.dll"))
            {
                var asm = Assembly.LoadFile(fn);
                var t = Helpers.GetTemplate(asm);
                var shortfn = new FileInfo(fn).Name;
                shortfn = shortfn.Substring(0, shortfn.LastIndexOf('.'));
                var path = outputDirPath;
                if (!Directory.Exists(path))
                {
                    try
                    {
                        Directory.CreateDirectory(path);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        Console.ReadKey();
                        return;
                    }
                }

                var rtv = JsonGen.Gen(t, path, shortfn.Substring("T_".Length));
                if (rtv)
                {
                    Console.WriteLine(rtv.ToString());
                    Console.ReadKey();
                    return;
                }
            }
        }
开发者ID:captainl1993,项目名称:dbtocpp,代码行数:46,代码来源:GenJsonMG.cs

示例4: Index

 public void Index()
 {
     Indexer indexer = new Indexer(new string[] { Environment.GetFolderPath(Environment.SpecialFolder.StartMenu) });
     Catalog catalog = new Catalog();
     List<string> items = indexer.Index();
     foreach (string item in items)
     {
         string name = new FileInfo(item).Name;
         catalog.Add(new CatalogItem() { Path = item, Name = name.Substring(0, name.Length - 4) });
     }
     _catalog = catalog;
     _catalog.Meta = new CatalogMeta { LastGenerated = DateTime.Now };
 }
开发者ID:itsbth,项目名称:DoIt,代码行数:13,代码来源:DoItManager.cs

示例5: loadsave

 public void loadsave()
 {
     myspacenamelist = new SpaceNameDictionary();
     string[] files = System.IO.Directory.GetFiles(root, "*.❣");
     for (int i = 0; i < files.Length; i++)
     {
         string filetext = System.IO.File.ReadAllText(files[i]);
         string filename=new System.IO.FileInfo(files[i]).Name;
         string head = filename.Substring(0, filename.Length - 2);
         string body = filetext.Substring(filetext.IndexOf(head));
         SpaceName sn = new SpaceName(head, body);
         myspacenamelist.Add(sn);
     }
 }
开发者ID:mirrorcomputing,项目名称:babyofearth,代码行数:14,代码来源:KingService.cs

示例6: LoadMessagesFromFiles

 public List<Message> LoadMessagesFromFiles()
 {
     var result = new List<Message>();
     try
     {
         foreach (var fileName in Directory.GetFiles(ExecutablePath.ExecPath + folder, "*.txt"))
         {
             var shortName = new FileInfo(fileName).Name;
             var roomName = shortName.Substring(0, shortName.LastIndexOf(".txt"));
             lock (fileLock)
             {
                 using (var fs = new FileStream(fileName, FileMode.OpenOrCreate))
                 using (var sr = new StreamReader(fs))
                 {
                     var lineNumber = 0;
                     while (true)
                     {
                         var line = sr.ReadLine();
                         if (string.IsNullOrEmpty(line))
                             break;
                         var words = line.Split(new[] {"&#32;"}, StringSplitOptions.None);
                         if (words.Length < 4)
                         {
                             Logger.Error(string.Format("LoadMessagesFromFiles: format error: file: {0}, line: {1}", fileName, lineNumber));
                             lineNumber++;
                             continue;
                         }
                         var message = new Message
                             {
                                 TimeStamp = DateTime.Parse(words[0]),
                                 Sender = words[1].ToInt(),
                                 Room = roomName,
                                 Receiver = words[2].ToInt(),
                                 Text = words[3].Replace("&#10;", Environment.NewLine)
                             };
                         result.Add(message);
                         lineNumber++;
                     }
                 }
             }
         }
     }
     catch (Exception exception)
     {
         Logger.Info("ChatClientStorage.LoadMessagesFromFiles", exception);
     }
     return result;
 }
开发者ID:johnmensen,项目名称:TradeSharp,代码行数:48,代码来源:ChatClientStorage.cs

示例7: InfoEFS

 public InfoEFS(string fichero)
 {
     string b = fichero.Substring (0, fichero.LastIndexOf('.'));
     string c = fichero.Substring (fichero.LastIndexOf('.')+1);
     if (b==String.Empty){
         // TODO: Poner una excepcion personalizada.
         throw new Exception ("...");
     }
     string tmp = new FileInfo (fichero).Name;
     tmp = tmp.Substring (0, tmp.LastIndexOf('.'));
     nombreOriginal = tmp;
     string nf = c.Substring (0, c.LastIndexOf("_")).Trim();
     string f = c.Substring (c.LastIndexOf ("_") + 1).Trim();
     Fragmento = Convert.ToInt32 (f);
     totalFragmentos = Convert.ToInt32 (nf);
 }
开发者ID:albfernandez,项目名称:dalle,代码行数:16,代码来源:InfoEFS.cs

示例8: LoadAvailableAssemblies

 /*метод, загружающий доступные исполняумые 
  * файлы из домашней директории проекта*/
 void LoadAvailableAssemblies()
 {
     //название файла сборки текущего приложения
     string except = new FileInfo(Application.ExecutablePath).Name;
     //получаем название файла без расширения
     except =  except.Substring(0, except.IndexOf("."));
     //получаем все *.exe файлы из домашней директории
     string[] files = Directory.GetFiles(Application.StartupPath, "*.exe");
     foreach (var file in files)
     {
         //получаем имя файла
         string fileName = new FileInfo(file).Name;
         /*если имя афйла не содержит имени исполняемого файла проекта, то оно добавляется в список*/
         if (fileName.IndexOf(except) == -1)
             AvailableAssemblies.Items.Add(fileName);
     }
 }
开发者ID:xs2ranjeet,项目名称:13ns9-1spr,代码行数:19,代码来源:MainWindow.cs

示例9: GetDatasets

 public static string[] GetDatasets(string root)
 {
   var subdirs = Directory.GetDirectories(root);
   Array.Sort(subdirs, delegate(string name1, string name2)
   {
     var n1 = new FileInfo(name1).Name;
     var n2 = new FileInfo(name2).Name;
     if (n1.StartsWith("GSE") && n2.StartsWith("GSE"))
     {
       return int.Parse(n1.Substring(3)).CompareTo(int.Parse(n2.Substring(3)));
     }
     else
     {
       return name1.CompareTo(name2);
     }
   });
   return subdirs;
 }
开发者ID:shengqh,项目名称:CQS.Core,代码行数:18,代码来源:SampleUtils.cs

示例10: button2_Click

 private void button2_Click(object sender, EventArgs e)
 {
     try
     {
         OpenFileDialog op = new OpenFileDialog();
         op.ShowDialog();
         textBox3.Text = op.FileName;
         //ProjectData.creteProject(textBox3.Text, dir);
         string name = new FileInfo(op.FileName).Name;
         name = name.Substring(0, name.IndexOf("."));
         Directory.CreateDirectory(ProjectData.parent + dir + "/" + name);
         ProjectData.creteFile(textBox3.Text, dir + "/" + name);
         textBox1.Text = ProjectData.openTextFile(textBox3.Text, dir + "/" + name);
         ProjectData.loadProject(dir, treeView1);
     }
     catch
     {
         MessageBox.Show("Upload a file");
     }
 }
开发者ID:sharma-nakul,项目名称:auto-text-summarization,代码行数:20,代码来源:Summarization.cs

示例11: GetHTML

        public String GetHTML()
        {
            String email = Resource1.Email;
            try
            {
                String shortName = new FileInfo(Filename).Name;
                String typArq = shortName.Substring(shortName.IndexOf("ACCC"), 7);
                String sTypArq = Utils.GetTypArq(typArq);

                email = email.Replace(MAIL_NOMARQ, shortName);
                email = email.Replace(MAIL_TIPARQ, typArq + " - " + sTypArq);
                email = email.Replace(MAIL_TAMARQ, Tamanho.ToString("F2") + " MB");
                email = email.Replace(MAIL_PRO, shortName.Contains("PRO.xml") ? "Sim" : "N&atilde;o");

                StringBuilder sb = new StringBuilder();

                //header
                sb.AppendLine(String.Format(MAIL_LINHA_HDR, "Cabe&ccedil;alho"));
                foreach (KeyValuePair<String, String> dado in Header)
                {
                    String value = dado.Value;
                    if (!value.Equals(String.Empty))
                    {
                        sb.AppendLine(String.Format(MAIL_LINHADADO_HDR, dado.Key, dado.Value));
                    }
                }
                //body
                sb.AppendLine(String.Format(MAIL_LINHA_HDR, "Dados"));
                foreach (KeyValuePair<String, String> dado in Body)
                {
                    sb.AppendLine(String.Format(MAIL_LINHADADO, dado.Key, dado.Value));
                }
                email = email.Replace(MAIL_DADOSARQ, sb.ToString());
            }
            catch (Exception ex)
            {
                if (Utils._logger != null)
                    Utils._logger.Error("Erro ao construir o body do email." + ex.Message);
            }
            return email;
        }
开发者ID:GregXP,项目名称:XP,代码行数:41,代码来源:ACCCxxx.cs

示例12: LoadAvailebleAssemblies

        public void LoadAvailebleAssemblies()
        {
            try
            {
                string except = new FileInfo(Application.ExecutablePath).Name;

                except = except.Substring(0, except.IndexOf("."));
                string[] files = Directory.GetFiles(Application.StartupPath, "*.exe");
                foreach (var file in files)
                {
                    string fileName = new FileInfo(file).Name;
                    if (fileName.IndexOf(except) == -1)
                    {
                        AvailebleAssemblies.Items.Add(fileName);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
开发者ID:RoykoSerhiy,项目名称:visualStudio_projects,代码行数:22,代码来源:Form1.cs

示例13: AddProjectInclude

        public async Task<bool> AddProjectInclude(string containerDirectory, string scriptFile = null)
        {
            if (!Project.Saved)
            {
                var saveDialogResult = MessageBox.Show(_ownerWindow, "Save pending changes to solution?",
                    "Save pending changes", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (saveDialogResult == DialogResult.OK || saveDialogResult == DialogResult.Yes)
                    _dte.SaveAll();
            }
            if (!Project.Saved || string.IsNullOrEmpty(Project.FullName))
            {
                var saveDialogResult = MessageBox.Show(_ownerWindow, "Pending changes need to be saved. Please save the project before adding project imports, then retry.", "Save first",
                    MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
                if (saveDialogResult != DialogResult.Cancel) _dte.SaveAll();
                return false;
            }
            _logger.LogInfo("Begin adding project import file");
            if (string.IsNullOrWhiteSpace(containerDirectory))
                containerDirectory = Project.GetDirectory();

            if (string.IsNullOrWhiteSpace(scriptFile))
            {
                _logger.LogInfo("Prompting for file name");
                var dialog = new AddBuildScriptNamePrompt(containerDirectory, ".targets")
                {
                    HideInvokeBeforeAfter = true
                };
                var dialogResult = dialog.ShowDialog(VsEnvironment.OwnerWindow);
                if (dialogResult == DialogResult.Cancel) return false;
                scriptFile = dialog.FileName;
                _logger.LogInfo("File name chosen: " + scriptFile);
                dialogResult = MessageBox.Show(_ownerWindow, @"        !! IMPORTANT !!

You must not move, rename, or remove this file once it has been added to the project. By adding this file you are extending the project file itself. If you must change the filename or location, you must update the project XML directly where <Import> references it.",
                    "This addition is permanent", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
                if (dialogResult == DialogResult.Cancel) return false;
            }
            var scriptFileName = scriptFile;
            if (!scriptFile.Contains(":") && !scriptFile.StartsWith("\\\\"))
                scriptFile = Path.Combine(containerDirectory, scriptFile);
            var scriptFileRelativePath = FileUtilities.GetRelativePath(Project.GetDirectory(), scriptFile);
            var scriptFileShortName = new FileInfo(scriptFile).Name;
            if (scriptFileShortName.Contains("."))
                scriptFileShortName = scriptFileShortName.Substring(0, scriptFileShortName.LastIndexOf("."));

            if (Project == null) return false;

            File.WriteAllText(scriptFile, @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
    <Target Name=""" + scriptFileShortName + @"""><!-- consider adding attrib BeforeTargets=""Build"" or AfterTargets=""Build"" -->

        <!-- my tasks here -->
        <Message Importance=""high"" Text=""" + scriptFileShortName + @".targets output: ProjectGuid = $(ProjectGuid)"" />

    </Target>
</Project>");
            var projRoot = Project.GetProjectRoot();
            var import = projRoot.AddImport(scriptFileRelativePath);
            import.Condition = "Exists('" + scriptFileRelativePath + "')";
            Project = await Project.SaveProjectRoot();
            var addedItem = Project.ProjectItems.AddFromFile(scriptFile);
            addedItem.Properties.Item("ItemType").Value = "None";
            _logger.LogInfo("Project include file added to project: " + scriptFileName);
            Task.Run(() =>
            {
                System.Threading.Thread.Sleep(250);
                _dte.ExecuteCommand("File.OpenFile", "\"" + scriptFile + "\"");
            });
            return true;
        }
开发者ID:freeart,项目名称:FastKoala,代码行数:69,代码来源:TargetsScriptInjector.cs

示例14: GetMapName

 private static string GetMapName(string file)
 {
     var name = new FileInfo(file).Name;
     return name.Substring(0, name.IndexOf(".txt", StringComparison.OrdinalIgnoreCase));
 }
开发者ID:xoposhiy,项目名称:icfpc2012,代码行数:5,代码来源:Correctness.cs

示例15: ms

        /*
         * see http://www.topografix.com/GPX/1/0 for more info
         *
         * Validating your GPX document
                Validation is done using the Xerces XML parser. Download the latest Xerces distribution from the Apache website.
                 Windows users should download the "Latest Xerces-C++ Binary Package for Windows". Unzip the files, and locate the
                 SAXCount.exe program in the bin folder. This is a command-line utility that will validate your GPX file.

            Assuming your GPX file is named my_gpx_file.gpx, and is located in the same folder as SaxCount.exe, use the following
             command line to validate your file:

                    SaxCount.exe -v=always -n -s -f test.gpx

            If your file validates successfully, SAXCount will display a count of the elements in your file, like the following:

                    test.gpx: 1012 ms (4025 elems, 1916 attrs, 8048 spaces, 36109 chars)

            Any other output from SAXCount.exe indicates that your GPX file is incorrect. It is your responsibility to ensure that any GPX files you create validate successfully against the GPX schema.
         */
        public void doWrite()
        {
            string diag = "Selected format: " + m_selectedFormat + "\r\n\r\n";
            trkpointCount = 0;
            waypointCount = 0;
            // could be "new DateTimeFormatInfo().UniversalSortableDateTimePattern;" - but it has space instead of 'T'

            messageBoxDirty = true;
            messageTextBox.Text = diag;

            try
            {
                if(m_selectedFormat.Equals(FileStreetsTripsCsv.FormatName))
                {
                    hasSaved = FileAndZipIO.saveCsv(m_selectedFileName, m_tracks, m_saveTracks,
                        m_waypoints, m_saveWaypoints, out waypointCount, out trkpointCount);
                }
                else if(m_selectedFormat.Equals(FileEasyGps.FormatName))
                {
                    int tracksCount;
                    hasSaved = FileAndZipIO.saveGpx(m_selectedFileName, m_tracks, m_saveTracks,
                        m_waypoints, m_saveWaypoints, out waypointCount, out trkpointCount, out tracksCount);

                    // try suggesting JPEG correlation here, if the folder has any .JPG files
                    if(tracksCount > 0)
                    {
                        bool hasJpegs = false;
                        try
                        {
                            FileInfo fi = new FileInfo(m_selectedFileName);
                            DirectoryInfo di = fi.Directory;
                            foreach(FileInfo fii in di.GetFiles())
                            {
                                if(fii.Name.ToLower().EndsWith(".jpg"))
                                {
                                    hasJpegs = true;
                                    break;
                                }
                            }
                        }
                        catch
                        {
                        }
                        if(hasJpegs)
                        {
                            string message = "The folder you selected contains images\r\n\r\nDo you want to relate them to trackpoints?";
                            if(Project.YesNoBox(this, message))
                            {
                                Project.photoFileName = m_selectedFileName;
                                Project.pmLastTabMode = 0;
                                DlgPhotoManager dlg = new DlgPhotoManager(0);
                                dlg.setImportButtonsAgitated();
                                dlg.ShowDialog();
                            }
                        }
                    }
                }
                else if(m_selectedFormat.Equals(FileKml.FormatName))
                {
                    string name = new FileInfo(m_selectedFileName).Name;

                    name = name.Substring(0, name.Length - FileKml.FileExtension.Length);

                    GoogleEarthManager.saveTracksWaypoints(
                        m_selectedFileName, name, m_tracks, m_saveTracks,
                        m_waypoints, m_saveWaypoints, out waypointCount, out trkpointCount
                    );
                }
                else
                {
                    messageTextBox.Text = "Error: format " + m_selectedFormat + " not supported for writing.";
                    LibSys.StatusBar.Error("FileExportForm:doWrite() format " + m_selectedFormat + " not supported for writing.");
                    return;
                }

                WaypointsCache.isDirty = false;

                if(waypointCount > 0 || trkpointCount > 0)
                {
                    diag += "OK: " + waypointCount + " waypoints and " + trkpointCount + " legs saved to file.";
                    messageTextBox.ForeColor = Color.Black;
//.........这里部分代码省略.........
开发者ID:slgrobotics,项目名称:QuakeMap,代码行数:101,代码来源:FileExportForm.cs


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