C# File.GetService的代码示例

通过代码示例来学习C# File.GetService方法

通过代码示例来学习编程是非常高效的。
1. 代码示例提供了一个具体而直观的学习环境,使初学者能够立即看到编程概念和语法的实际应用。
2. 通过分析和模仿现有的代码实例,初学者可以更好地理解编程逻辑和算法的工作原理。
3. 代码实例往往涵盖了多种编程技巧和最佳实践,通过学习和模仿这些实例,学习者可以逐步掌握如何编写高效、可读性强和可维护的代码。这对于初学者来说,是一种快速提升编程水平的有效途径。


File.GetService是C#的System.IO命名空间下中的一个方法, 小编为大家找了一些网络大拿们常见的代码示例,源码中的File.GetService() 已经帮大家高亮显示了,大家可以重点学习File.GetService() 方法的写法,从而快速掌握该方法的应用。

File.GetService的代码示例1 - SetEditLabel()

    using System.IO;

        /// 
        /// Rename Folder
        /// 
        /// new Name of Folder
        /// VSConstants.S_OK, if succeeded
        public override int SetEditLabel(string label)
        {
            if(String.Compare(Path.GetFileName(this.Url.TrimEnd('\\')), label, StringComparison.Ordinal) == 0)
            {
                // Label matches current Name
                return VSConstants.S_OK;
            }

            string newPath = Path.Combine(new DirectoryInfo(this.Url).Parent.FullName, label);

            // Verify that No Directory/file already exists with the new name among current children
            for(HierarchyNode n = Parent.FirstChild; n != null; n = n.NextSibling)
            {
                if(n != this && String.Compare(n.Caption, label, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    return ShowFileOrFolderAlreadExistsErrorMessage(newPath);
                }
            }

            // Verify that No Directory/file already exists with the new name on disk
            if(Directory.Exists(newPath) || File.Exists(newPath))
            {
                return ShowFileOrFolderAlreadExistsErrorMessage(newPath);
            }

            try
            {
                RenameFolder(label);

                //Refresh the properties in the properties window
                IVsUIShell shell = this.ProjectMgr.GetService(typeof(SVsUIShell)) as IVsUIShell;
                Debug.Assert(shell != null, "Could not get the ui shell from the project");
                ErrorHandler.ThrowOnFailure(shell.RefreshPropertyBrowser(0));

                // Notify the listeners that the name of this folder is changed. This will
                // also force a refresh of the SolutionExplorer's node.
                this.OnPropertyChanged(this, (int)__VSHPROPID.VSHPROPID_Caption, 0);
            }
            catch(Exception e)
            {
                throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.RenameFolder, CultureInfo.CurrentUICulture), e.Message));
            }
            return VSConstants.S_OK;
        }
    

开发者ID:EWSoftware,项目名称:SHFB,代码行数:51,代码来源:FolderNode.cs

在SetEditLabel()方法中,File的代码示例类中的GetService的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞

File.GetService的代码示例2 - SaveItem()

    using System.IO;

        /// 
        /// Saves the hierarchy item to disk.
        /// 
        /// Flags whose values are taken from the VSSAVEFLAGS enumeration.
        /// File name to be applied when dwSave is set to VSSAVE_SilentSave. 
        /// Item identifier of the hierarchy item saved from VSITEMID. 
        /// Pointer to the IUnknown interface of the hierarchy item saved.
        /// TRUE if the save action was canceled. 
        /// If the method succeeds, it returns S_OK. If it fails, it returns an error code.
        public override int SaveItem(VSSAVEFLAGS dwSave, string silentSaveAsName, uint itemid, IntPtr punkDocData, out int pfCancelled)
        {
            // Don't ignore/unignore file changes 
            // Use Advise/Unadvise to work around rename situations
            try
            {
                this.StopObservingNestedProjectFile();
                Debug.Assert(this.nestedHierarchy != null, "The nested hierarchy object must be created before calling this method");
                Debug.Assert(punkDocData != IntPtr.Zero, "docData intptr was zero");

                // Get an IPersistFileFormat object from docData object (we don't call release on punkDocData since did not increment its ref count)
                IPersistFileFormat persistFileFormat = Marshal.GetTypedObjectForIUnknown(punkDocData, typeof(IPersistFileFormat)) as IPersistFileFormat;
                Debug.Assert(persistFileFormat != null, "The docData object does not implement the IPersistFileFormat interface");

                IVsUIShell uiShell = this.GetService(typeof(SVsUIShell)) as IVsUIShell;
                string newName;
                ErrorHandler.ThrowOnFailure(uiShell.SaveDocDataToFile(dwSave, persistFileFormat, silentSaveAsName, out newName, out pfCancelled));

                // When supported do a rename of the nested project here 
            }
            finally
            {
                // Succeeded or not we must hook to the file change events
                // Don't ignore/unignore file changes 
                // Use Advise/Unadvise to work around rename situations
                this.ObserveNestedProjectFile();
            }

            return VSConstants.S_OK;
        }
    

开发者ID:EWSoftware,项目名称:SHFB,代码行数:41,代码来源:NestedProjectNode.cs

在SaveItem()方法中,File的代码示例类中的GetService的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞

File.GetService的代码示例3 - RenameProjectFile()

    using System.IO;

        /// 
        /// Renames the project file
        /// 
        /// The full path of the new project file.
        protected virtual void RenameProjectFile(string newFile)
        {
            IVsUIShell shell = this.Site.GetService(typeof(SVsUIShell)) as IVsUIShell;
            Debug.Assert(shell != null, "Could not get the UI shell from the project");
            if (shell == null)
            {
                throw new InvalidOperationException();
            }

            // Do some name validation
            if (Utilities.ContainsInvalidFileNameChars(newFile))
            {
                throw new InvalidOperationException(SR.GetString(SR.ErrorInvalidProjectName, CultureInfo.CurrentUICulture));
            }

            // Figure out what the new full name is
            string oldFile = this.Url;

            IVsSolution vsSolution = (IVsSolution)this.GetService(typeof(SVsSolution));

            if (ErrorHandler.Succeeded(vsSolution.QueryRenameProject(this.InteropSafeIVsProject3, oldFile, newFile, 0, out int canContinue))
                && canContinue != 0)
            {
                bool isFileSame = NativeMethods.IsSamePath(oldFile, newFile);

                // If file already exist and is not the same file with different casing
                if (!isFileSame && File.Exists(newFile))
                {
                    // Prompt the user for replace
                    string message = SR.GetString(SR.FileAlreadyExists, newFile);

                    if (!Utilities.IsInAutomationFunction(this.Site))
                    {
                        if (!VsShellUtilities.PromptYesNo(message, null, OLEMSGICON.OLEMSGICON_WARNING, shell))
                        {
                            throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
                        }
                    }
                    else
                    {
                        throw new InvalidOperationException(message);
                    }

                    // Delete the destination file after making sure it is not read only
                    File.SetAttributes(newFile, FileAttributes.Normal);
                    File.Delete(newFile);
                }

                SuspendFileChanges fileChanges = new SuspendFileChanges(this.Site, this.filename);
                fileChanges.Suspend();
                try
                {
                    // Actual file rename
                    this.SaveMSBuildProjectFileAs(newFile);

                    this.SetProjectFileDirty(false);

                    if (!isFileSame)
                    {
                        // Now that the new file name has been created delete the old one.
                        // TODO: Handle source control issues.
                        File.SetAttributes(oldFile, FileAttributes.Normal);
                        File.Delete(oldFile);
                    }

                    this.OnPropertyChanged(this, (int)__VSHPROPID.VSHPROPID_Caption, 0);

                    // Update solution
                    ErrorHandler.ThrowOnFailure(vsSolution.OnAfterRenameProject(this.InteropSafeIVsProject3, oldFile, newFile, 0));

                    ErrorHandler.ThrowOnFailure(shell.RefreshPropertyBrowser(0));
                }
                finally
                {
                    fileChanges.Resume();
                }
            }
            else
            {
                throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
            }
        }
    

开发者ID:EWSoftware,项目名称:SHFB,代码行数:88,代码来源:ProjectNode.cs

在RenameProjectFile()方法中,File的代码示例类中的GetService的代码示例方法一共出现了2次, 见黄色背景高亮显示的地方,欢迎大家点赞

File.GetService的代码示例4 - ShowObjectBrowser()

    using System.IO;


        /// 
        /// Shows the Object Browser
        /// 
        /// 
        protected virtual int ShowObjectBrowser()
        {
            if(String.IsNullOrEmpty(this.Url) || !File.Exists(this.Url))
            {
                return (int)OleConstants.OLECMDERR_E_NOTSUPPORTED;
            }

            // Request unmanaged code permission in order to be able to creaet the unmanaged memory representing the guid.
            new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();

            Guid guid = VSConstants.guidCOMPLUSLibrary;
            IntPtr ptr = System.Runtime.InteropServices.Marshal.AllocCoTaskMem(guid.ToByteArray().Length);

            System.Runtime.InteropServices.Marshal.StructureToPtr(guid, ptr, false);
            int returnValue = VSConstants.S_OK;
            try
            {
                VSOBJECTINFO[] objInfo = new VSOBJECTINFO[1];

                objInfo[0].pguidLib = ptr;
                objInfo[0].pszLibName = this.Url;

                IVsObjBrowser objBrowser = this.ProjectMgr.Site.GetService(typeof(SVsObjBrowser)) as IVsObjBrowser;

                ErrorHandler.ThrowOnFailure(objBrowser.NavigateTo(objInfo, 0));
            }
            catch(COMException e)
            {
                Trace.WriteLine("Exception" + e.ErrorCode);
                returnValue = e.ErrorCode;
            }
            finally
            {
                if(ptr != IntPtr.Zero)
                {
                    System.Runtime.InteropServices.Marshal.FreeCoTaskMem(ptr);
                }
            }

            return returnValue;
        }
    

开发者ID:EWSoftware,项目名称:SHFB,代码行数:48,代码来源:ReferenceNode.cs

在ShowObjectBrowser()方法中,File的代码示例类中的GetService的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞

File.GetService的代码示例5 - UpdateGeneratedCodeFile()

    using System.IO;

        /// 
        /// This is called after the single file generator has been invoked to create or update the code file.
        /// 
        /// The node associated to the generator
        /// data to update the file with
        /// size of the data
        /// Name of the file to update or create
        /// full path of the file
        protected virtual string UpdateGeneratedCodeFile(FileNode fileNode, byte[] data, int size, string fileName)
        {
            string filePath = Path.Combine(Path.GetDirectoryName(fileNode.GetMkDocument()), fileName);
            IVsRunningDocumentTable rdt = this.projectMgr.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable;

            // (kberes) Shouldn't this be an InvalidOperationException instead with some not to annoying errormessage to the user?
            if(rdt == null)
            {
                ErrorHandler.ThrowOnFailure(VSConstants.E_FAIL);
            }

            IVsHierarchy hier;
            uint cookie;
            uint itemid;
            IntPtr docData = IntPtr.Zero;
            ErrorHandler.ThrowOnFailure(rdt.FindAndLockDocument((uint)(_VSRDTFLAGS.RDT_NoLock), filePath, out hier, out itemid, out docData, out cookie));
            if(docData != IntPtr.Zero)
            {
                Marshal.Release(docData);
                IVsTextStream srpStream = null;
                if(srpStream != null)
                {
                    int oldLen = 0;
                    int hr = srpStream.GetSize(out oldLen);
                    if(ErrorHandler.Succeeded(hr))
                    {
                        IntPtr dest = IntPtr.Zero;
                        try
                        {
                            dest = Marshal.AllocCoTaskMem(data.Length);
                            Marshal.Copy(data, 0, dest, data.Length);
                            ErrorHandler.ThrowOnFailure(srpStream.ReplaceStream(0, oldLen, dest, size / 2));
                        }
                        finally
                        {
                            if(dest != IntPtr.Zero)
                            {
                                Marshal.Release(dest);
                            }
                        }
                    }
                }
            }
            else
            {
                using(FileStream generatedFileStream = File.Open(filePath, FileMode.OpenOrCreate))
                {
                    generatedFileStream.Write(data, 0, size);
                }

                EnvDTE.ProjectItem projectItem = fileNode.GetAutomationObject() as EnvDTE.ProjectItem;
                if(projectItem != null && (this.projectMgr.FindChild(fileNode.FileName) == null))
                {
                    projectItem.ProjectItems.AddFromFile(filePath);
                }
            }
            return filePath;
        }
    

开发者ID:EWSoftware,项目名称:SHFB,代码行数:68,代码来源:SingleFileGenerator.cs

在UpdateGeneratedCodeFile()方法中,File的代码示例类中的GetService的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞

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