Programing

Visual Studio bin 및 obj 폴더를 정리하는 방법

lottogame 2020. 10. 18. 08:21
반응형

Visual Studio bin 및 obj 폴더를 정리하는 방법


폴더를 마우스 오른쪽 버튼으로 클릭하면 "Clean"메뉴 항목이 표시됩니다. 나는 이것이 obj 및 bin 디렉토리를 정리 (제거)한다고 가정했습니다. 그러나 내가 볼 수있는 한 아무것도하지 않는다. 다른 방법이 있습니까? (Windows 탐색기 또는 cmd.exe로 이동하라고 말하지 마십시오.) 모든 것을 쉽게 압축 할 수 있도록 obj 및 bin 폴더를 제거하고 싶습니다.


다른 사람들이 이미 응답 했으므로 Clean은 빌드에서 생성 된 모든 아티팩트를 제거합니다. 그러나 그것은 다른 모든 것을 남겨 둘 것입니다.

MSBuild 프로젝트에 일부 사용자 지정이있는 경우 문제를 일으킬 수 있으며 삭제해야한다고 생각하는 항목이 남을 수 있습니다.

. * proj를 간단히 변경하여이 문제를 피할 수 있습니다.

<Target Name="SpicNSpan"
        AfterTargets="Clean">
    <RemoveDir Directories="$(OUTDIR)"/>
</Target>

현재 플랫폼 / 구성의 bin 폴더에있는 모든 항목이 제거됩니다.

------ 아래 주술사의 답변 에 따라 약간의 진화를 편집하십시오 (투표를 공유하고 그에게도 제공)

<Target Name="SpicNSpan"  AfterTargets="Clean">
    <!-- Remove obj folder -->
    <RemoveDir Directories="$(BaseIntermediateOutputPath)" />
    <!-- Remove bin folder -->
    <RemoveDir Directories="$(BaseOutputPath)" />
</Target>

---- xDisruptor의 일부로 다시 편집 하지만 .gitignore (또는 이와 동등한)에서 더 잘 제공되므로 .vs 삭제를 제거했습니다.

VS 2015 용으로 업데이트되었습니다.

<Target Name="SpicNSpan" AfterTargets="Clean"> <!-- common vars https://msdn.microsoft.com/en-us/library/c02as0cs.aspx?f=255&MSPPError=-2147217396 -->
     <RemoveDir Directories="$(TargetDir)" /> <!-- bin -->
     <RemoveDir Directories="$(ProjectDir)$(BaseIntermediateOutputPath)" /> <!-- obj -->
</Target>

그는 또한 이것을 푸시 할 여러 프로젝트가있는 경우 작업을보다 쉽게 ​​배포하고 유지 관리 할 수있는 좋은 제안을 제공합니다.

이 답변에 투표하는 경우 둘 다 투표해야합니다.


Visual Studio 2015의 경우 MSBuild 변수가 약간 변경되었습니다.

  <Target Name="SpicNSpan" AfterTargets="Clean"> <!-- common vars https://msdn.microsoft.com/en-us/library/c02as0cs.aspx?f=255&MSPPError=-2147217396 -->
         <RemoveDir Directories="$(TargetDir)" /> <!-- bin -->
         <RemoveDir Directories="$(SolutionDir).vs" /> <!-- .vs -->
         <RemoveDir Directories="$(ProjectDir)$(BaseIntermediateOutputPath)" /> <!-- obj -->
  </Target>

이 스 니펫은 솔루션의 루트 디렉터리에서 .vs 폴더도 지 웁니다. .vs 폴더를 제거하는 것이 과도하다고 생각되면 관련 줄을 주석 처리 할 수 ​​있습니다. 일부 타사 프로젝트에서 .vs 폴더 내에 application.config 파일이 존재할 때 문제가 발생한다는 것을 알았 기 때문에 활성화했습니다.

추가:

솔루션의 유지 관리 가능성을 최적화하려면 한 단계 더 나아가 위의 스 니펫을 다음과 같이 별도의 파일에 배치하는 것이 좋습니다.

  <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
       <Target Name="SpicNSpan" AfterTargets="Clean"> <!-- common vars https://msdn.microsoft.com/en-us/library/c02as0cs.aspx?f=255&MSPPError=-2147217396 -->
            <RemoveDir Directories="$(TargetDir)" /> <!-- bin -->
            <RemoveDir Directories="$(SolutionDir).vs" /> <!-- .vs -->
            <RemoveDir Directories="$(ProjectDir)$(BaseIntermediateOutputPath)" /> <!-- obj -->
       </Target>
  </Project>

그런 다음 다음과 같이 * .csproj 파일의 각 끝에이 파일을 포함합니다.

     [...]
     <Import Project="..\..\Tools\ExtraCleanup.targets"/>
  </Project>

이렇게하면 개선을 원할 때마다 모든 * .csproj 파일을 수동으로 편집해야하는 번거 로움없이 중앙에서 중앙 집중식으로 추가 정리 로직을 강화하거나 미세 조정할 수 있습니다.


git을 사용 .gitignore하고 있고 프로젝트에 올바른 정보가있는 경우 다음을 수행 할 수 있습니다.

git clean -xdf --dry-run

.gitignore목록 에있는 모든 파일을 완전히 제거 합니다. 즉, 정리 objbin폴더 ( x이 동작이 트리거 됨)


빌드하기 전에 bin 및 obj를 삭제하려면 프로젝트 파일에 추가하십시오.

<Target Name="BeforeBuild">
    <!-- Remove obj folder -->
    <RemoveDir Directories="$(BaseIntermediateOutputPath)" />
    <!-- Remove bin folder -->
    <RemoveDir Directories="$(BaseOutputPath)" />
</Target>

다음은 기사입니다 : 빌드 또는 배포 전에 bin 및 / 또는 obj 폴더를 제거하는 방법


Ron Jacobs의 환상적인 오픈 소스 CleanProject를 확인하십시오 . 원하는 경우 압축도 처리합니다.

다음은 CodePlex 링크입니다.


이 사이트 : https://sachabarbs.wordpress.com/2014/10/24/powershell-to-clean-visual-studio-binobj-folders/ 는 powershell을 사용하여 현재 디렉터리 및 하위 디렉터리에서 bin 및 obj 폴더를 제거합니다. 드라이브의 루트에서 실행할 수 있어야합니다. 기사에서 인용 한 내용은 다음과 같습니다.

다음은 Williams 버전입니다.

 gci -inc bin,obj -rec | rm -rec -force

윌리엄스 자신의 말로

그러면 현재 디렉토리와 모든 하위 디렉토리에있는 모든 "bin"및 "obj"디렉토리가 지워집니다. 특히 누군가가 엉망이되어 IDE 내부의 Clean 또는 Rebuild가 포착하지 못하는 무언가가있을 때 "깨끗한"상태를 얻기 위해 작업 공간 디렉토리에서 실행하는 것이 매우 유용합니다.

모르는 분들을 위해 PowerShell은 명령 별칭을 지원합니다. 여기서 별칭을 사용하지 않고 다시 작성됩니다.

Get-ChildItem -inc bin,obj -rec | Remove-Item -rec -force

참고 :이 파일을 PowerShell 파일에 저장하고 해당 파일을 솔루션의 루트 (.sln 파일이있는 위치)에 배치 한 다음 적절한 정리를 원할 때 실행해야합니다 (VisualStudio가 수행하는 미키 마우스가 아닌, 성공도보고합니다).


폴더를 제거하지는 않지만 빌드 부산물은 제거합니다. 실제 빌드 폴더를 제거 하려는 이유가 있습니까?


Clean은 .obj 파일 및 .exe 또는 .dll 파일과 같이 빌드 프로세스에서 생성 된 모든 중간 및 최종 파일을 제거합니다.

그러나 해당 파일이 빌드 된 디렉토리는 제거하지 않습니다. 디렉토리를 제거해야하는 설득력있는 이유가 보이지 않습니다. 더 설명해 주시겠습니까?

"Clean"전후에이 디렉토리를 살펴보면 컴파일 된 출력이 정리되는 것을 볼 수 있습니다.


Far Manager에서 binobj 폴더를 쉽게 찾고 제거 할 수 있습니다 .

  1. 솔루션으로 이동하고 Alt + F7을 누릅니다.
  2. 검색 설정 대화 상자에서 :

    • " 파일 마스크 또는 여러 파일 마스크"필드에 "bin, obj" 를 입력합니다.
    • "폴더 검색" 옵션을 선택하십시오.
    • 엔터 키를 치시오
  3. 검색이 완료되면 보기를 "Panel"로 전환합니다 .

  4. 모든 파일 선택 (Ctrl + A 사용) 및 폴더 삭제 ( "Shift + Del"누름)

누군가에게 도움이되기를 바랍니다.


아직 코멘트를 추가 할 수 없으므로 (최소한의 평판에 도달하지 못함) 다음과
같은 내용에 밑줄을 긋기 위해이 답변을 남겨 둡니다.

"BeforeBuild"작업 <RemoveDir Directories="$(BaseIntermediateOutputPath)" />은 훌륭하지만 저에게는 동일한 프로젝트에 포함 된 Entity Framework 모델과 충돌합니다.

내가받는 오류는 다음과 같습니다.

Error reading resource '{mymodel}.csdl' -- 'Could not find a part of the path '{myprojectpath}\obj\Release\edmxResourcesToEmbed\{mymodel}.csdl

"BeforeBuild"대상 작업이 실행되기 전에 "edmxResourcesToembed"가 생성되었다고 가정합니다.


이해하기 쉽고 예측 가능한 VisualStudioClean사용 합니다. 작동 방식과 삭제할 파일을 알면 안심할 수 있습니다.

Previously I tried VSClean (note VisualStudioClean is not VSClean), VSClean is more advanced, it has many configurations that sometimes makes me wondering what files it is going to delete? One mis-configuration will result in lose of my source codes. Testing how the configuration will work need backing up all my projects which take a lot of times, so in the end I choose VisualStudioClean instead.

Conclusion : VisualStudioClean if you want basic cleaning, VSClean for more complex scenario.


This is how I do with a batch file to delete all BIN and OBJ folders recursively.

  • Create an empty file and name it DeleteBinObjFolders.bat
  • Copy-paste code the below code into the DeleteBinObjFolders.bat
  • Move the DeleteBinObjFolders.bat file in the same folder with your solution (*.sln) file.
@echo off
@echo Deleting all BIN and OBJ folders...
for /d /r . %%d in (bin,obj) do @if exist "%%d" rd /s/q "%%d"
@echo BIN and OBJ folders successfully deleted :) Close the window.
pause > nul

Based on Joe answer, I've converted the VB code into C# :

/// <summary>
/// Based on code of VSProjCleaner tool (C) 2005 Francesco Balena, Code Archirects
/// </summary>
static class VisualStudioCleaner
{
    public static void Process(string rootDir)
    {
        // Read all the folder names in the specified directory tree
        string[] dirNames = Directory.GetDirectories(rootDir, "*.*", SearchOption.AllDirectories);
        List<string> errorsList = new List<string>();

        // delete any .suo and csproj.user file
        foreach (string dir in dirNames) {
            var files = new List<string>();
            files.AddRange(Directory.GetFiles(dir, "*.suo"));
            files.AddRange(Directory.GetFiles(dir, "*.user"));
            foreach (string fileName in files) {
                try {
                    Console.Write("Deleting {0} ...", fileName);
                    File.Delete(fileName);
                    Console.WriteLine("DONE");
                } catch (Exception ex) {
                    Console.WriteLine();
                    Console.WriteLine(" ERROR: {0}", ex.Message);
                    errorsList.Add(fileName + ": " + ex.Message);
                }
            }
        }

        // Delete all the BIN and OBJ subdirectories
        foreach (string dir in dirNames) {
            string dirName = Path.GetFileName(dir).ToLower();
            if (dirName == "bin" || dirName == "obj") {
                try {
                    Console.Write("Deleting {0} ...", dir);
                    Directory.Delete(dir, true);
                    Console.WriteLine("DONE");
                } catch (Exception ex) {
                    Console.WriteLine();
                    Console.WriteLine(" ERROR: {0}", ex.Message);
                    errorsList.Add(dir + ": " + ex.Message);
                }
            }
        }
        Console.WriteLine(new string('-', 60));
        if (errorsList.Count == 0) {
            Console.WriteLine("All directories and files were removed successfully");
        } else {
            Console.WriteLine("{0} directories or directories couldn't be removed", errorsList.Count);
            Console.WriteLine(new string('-', 60));
            foreach (string msg in errorsList) {
                Console.WriteLine(msg);
            }
        }
    }
}

I store my finished VS projects by saving only source code.

I delete BIN, DEBUG, RELEASE, OBJ, ARM and .vs folders from all projects.

This reduces the size of the project considerably. The project

must be rebuilt when pulled out of storage.


Just an addendum to all the fine answers above in case someone doesn't realize how easy it is in VB/C# to automate the entire process down to the zip archive.

So you just grab a simple Forms app from the templates (if you don't already have a housekeeping app) and add a button to it and then ClickOnce install it to your desktop without worrying about special settings or much of anything. This is all the code you need to attach to the button:

Imports System.IO.Compression

Private Sub btnArchive_Click(sender As Object, e As EventArgs) Handles btnArchive.Click
    Dim src As String = "C:\Project"
    Dim dest As String = Path.Combine("D:\Archive", "Stub" & Now.ToString("yyyyMMddHHmmss") & ".zip")
    If IsProjectOpen() Then 'You don't want Visual Studio holding a lock on anything while you're deleting folders
        MsgBox("Close projects first, (expletive deleted)", vbOKOnly)
        Exit Sub
    End If
    If MsgBox("Are you sure you want to delete bin and obj folders?", vbOKCancel) = DialogResult.Cancel Then Exit Sub
    If ClearBinAndObj(src) Then ZipFile.CreateFromDirectory(src, dest)
End Sub

Public Function ClearBinAndObj(targetDir As String) As Boolean
    Dim dirstodelete As New List(Of String)
    For Each d As String In My.Computer.FileSystem.GetDirectories(targetDir, FileIO.SearchOption.SearchAllSubDirectories, "bin")
        dirstodelete.Add(d)
    Next
    For Each d As String In My.Computer.FileSystem.GetDirectories(targetDir, FileIO.SearchOption.SearchAllSubDirectories, "obj")
        dirstodelete.Add(d)
    Next
    For Each d In dirstodelete
        Try
            Directory.Delete(d, True)
        Catch ex As Exception
            If MsgBox("Error: " & ex.Message & " - OK to continue?", vbOKCancel) = MsgBoxResult.Cancel Then Return False
        End Try
    Next
    Return True
End Function

Public Function IsProjectOpen()
    For Each clsProcess As Process In Process.GetProcesses()
        If clsProcess.ProcessName.Equals("devenv") Then Return True
    Next
    Return False
End Function

One thing to remember is that file system deletes can go wrong easily. One of my favorites was when I realized that I couldn't delete a folder because it contained items created by Visual Studio while running with elevated privileges (so that I could debug a service).

I needed to manually give permission or, I suppose, run the app with elevated privileges also. Either way, I think there is some value in using an interactive GUI-based approach over a script, specially since this is likely something that is done at the end of a long day and you don't want to find out later that your backup doesn't actually exist...

참고URL : https://stackoverflow.com/questions/1088593/how-to-clean-visual-studio-bin-and-obj-folders

반응형