Windows的C盘瘦身计划

C盘总是容易满了,于是打算瘦身。

常规操作当然是首先把虚拟内存迁移,把桌面文件迁移,删掉【下载】文件夹里的文件,平时安装文件不要安装到C盘。等等。

一、进去C:\Users\Administrator\AppData\Local\Temp路径,可以将这些临时文件全部删除,释放内存空间。

二、使用CCleaner。

然后,建议先用spacesniffer检查一下C盘,或者可以直接输入可疑的文件夹:

C:\Users\Administrator\AppData\Roaming

C:\Users\Administrator\AppData\Local

C:\ProgramData

 

也可以使用WizTree:

QQ_1759980117512

 

参考文章:C盘清理——“C:\ProgramData\Package Cache“文件夹转移 :https://blog.csdn.net/qq_40206657/article/details/130917738

首先是复制,用管理员运行cmd,输入:xcopy /e "C:\ProgramData\Package Cache" "F:\ProgramData\Package Cache"

大约一两分钟就搞定了4.6G的复制。紧接着,改名、建立链接:

ren "C:\ProgramData\Package Cache" "Package Cache0"
mklink /J "C:\ProgramData\Package Cache" "F:\ProgramData\Package Cache"

发现没有啥问题后,进入目录并删掉 C:\ProgramData\Package Cache0,然后清理回收站吧。或者直接输入:rd /s /q "C:\ProgramData\Package Cache0"

 AI 帮我写成了python代码,更加简便(我后来保存python为:migrate把C盘文件移动link到其它盘.py):

# -*- coding: utf-8 -*-
import os
import sys
import shutil
import ctypes
import subprocess

def is_admin():
    try:
        return ctypes.windll.shell32.IsUserAnAdmin()
    except:
        return False

def request_admin():
    """以管理员身份重新启动自己"""
    ctypes.windll.shell32.ShellExecuteW(
        None, "runas", sys.executable, ' '.join([f'"{sys.argv[0]}"']), None, 1
    )
    sys.exit()

def pause_exit(code=0):
    input("\nPress Enter to exit...")
    sys.exit(code)

def is_junction(path):
    """检查路径是否是 Junction 链接"""
    try:
        result = subprocess.check_output(
            ['dir', path], shell=True, stderr=subprocess.STDOUT
        ).decode('gbk', errors='ignore')
        return '<JUNCTION>' in result
    except:
        return False

def is_root_dir(path):
    """检查是否是根目录,如 C:\\ 或 F:\\"""
    return len(path) <= 3 and path[1:] in (':\\', ':/')

def get_folder_name(path):
    return os.path.basename(path.rstrip('\\/'))

def main():
    print("=" * 44)
    print("  Folder Migration Tool (Python, Win7 OK)")
    print("=" * 44)
    print()

    # ── 检查管理员权限 ──────────────────────────
    if not is_admin():
        print("[INFO] Not running as admin. Requesting elevation...")
        request_admin()
        return

    print("[OK] Admin rights confirmed.")
    print()

    # ── 输入源路径 ──────────────────────────────
    while True:
        print("[Step 1] Enter the SOURCE folder path to migrate.")
        print(r"Example: C:\Users\Administrator\AppData\Local\JianyingPro")
        print()
        source_path = input("Enter source path: ").strip().strip('"')

        if not source_path:
            print("[ERROR] Path cannot be empty. Please try again.\n")
            continue

        if is_root_dir(source_path):
            print("[ERROR] Cannot use root directory! Please try again.\n")
            continue

        if not os.path.isdir(source_path):
            print(f"[ERROR] Source path does not exist: {source_path}\n")
            continue

        if is_junction(source_path):
            print(f"[WARNING] '{source_path}' is already a Junction link!")
            print("          Migration may have already been done. Aborting.\n")
            pause_exit(1)

        break

    # ── 提取盘符和子路径 ────────────────────────
    source_drive = source_path[:2]           # 例如 C:
    source_subpath = source_path[2:]         # 例如 \Users\Administrator\...
    folder_name = get_folder_name(source_path)
    source_backup = source_path + "0"        # 例如 ...JianyingPro0

    # ── 输入目标盘符 ────────────────────────────
    while True:
        print()
        print("[Step 2] Enter the TARGET drive letter (e.g.: F)")
        print("         The folder will be migrated to the same path on that drive.")
        print()
        target_drive = input("Enter target drive letter: ").strip().strip('"').replace(':', '').upper()

        if not target_drive:
            print("[ERROR] Drive letter cannot be empty. Please try again.\n")
            continue

        if len(target_drive) != 1 or not target_drive.isalpha():
            print("[ERROR] Please enter only a single drive letter (e.g.: F).\n")
            continue

        if target_drive.upper() == source_drive[0].upper():
            print(f"[ERROR] Target drive cannot be the same as source drive ({source_drive})!\n")
            continue

        target_root = target_drive + ":\\"
        if not os.path.isdir(target_root):
            print(f"[ERROR] Drive {target_root} does not exist or is not accessible.\n")
            continue

        break

    # ── 推算目标路径 ────────────────────────────
    target_path = target_drive + ":" + source_subpath

    # ── 检查目标路径是否已存在 ──────────────────
    if os.path.isdir(target_path):
        print()
        print(f"[WARNING] Target path already exists: {target_path}")
        print("          Continuing may overwrite or merge existing content!")
        print()
        confirm = input("Continue anyway? (Type YES to continue, anything else to cancel): ").strip()
        if confirm.upper() != "YES":
            print("Cancelled.")
            pause_exit(0)

    # ── 二次确认 ────────────────────────────────
    print()
    print("=" * 44)
    print("  Please confirm the following operations:")
    print("=" * 44)
    print()
    print(f"  [1] Copy source : {source_path}")
    print(f"  [2] Copy target : {target_path}")
    print(f"  [3] Rename      : {source_path}  ->  {source_backup}")
    print(f"  [4] Create link : {source_path}  ->  {target_path}")
    print()
    print(f"  After confirming all is well, you may delete:")
    print(f"  {source_backup}")
    print()
    print("=" * 44)
    print()
    confirm = input("Is everything correct? Type YES to confirm, anything else to cancel: ").strip()
    if confirm.upper() != "YES":
        print("Cancelled.")
        pause_exit(0)

    print()
    print("[Starting migration...]")
    print()

    # ── 步骤 1:复制 ────────────────────────────
    print("[Step 1/3] Copying files, please wait...")
    try:
        shutil.copytree(source_path, target_path)
        print("[OK] Copy complete.\n")
    except Exception as e:
        print(f"[ERROR] Copy failed: {e}")
        print("        Check disk space and permissions.")
        pause_exit(1)

    # ── 步骤 2:改名原目录 ──────────────────────
    print(f'[Step 2/3] Renaming original folder to "{folder_name}0"...')
    try:
        os.rename(source_path, source_backup)
        print("[OK] Rename complete.\n")
    except Exception as e:
        print(f"[ERROR] Rename failed: {e}")
        print("        Check if any program is using the folder.")
        pause_exit(1)

    # ── 步骤 3:建立 Junction 链接 ──────────────
    print("[Step 3/3] Creating Junction link...")
    try:
        result = subprocess.call(
            f'mklink /J "{source_path}" "{target_path}"',
            shell=True
        )
        if result != 0:
            raise Exception(f"mklink returned exit code {result}")
        print("[OK] Junction link created.\n")
    except Exception as e:
        print(f"[ERROR] Failed to create Junction link: {e}")
        print("        Attempting to restore renamed folder...")
        try:
            os.rename(source_backup, source_path)
            print("        Restored successfully.")
        except Exception as re:
            print(f"        Restore also failed: {re}")
        pause_exit(1)

    # ── 完成 ────────────────────────────────────
    print("=" * 44)
    print("  [OK] Migration completed successfully!")
    print("=" * 44)
    print()
    print(f"  Backup folder : {source_backup}")
    print(f"  Junction link : {source_path}")
    print(f"  Actual storage: {target_path}")
    print()
    print("  If everything works correctly, you may")
    print("  manually delete the backup to free up space:")
    print(f"  {source_backup}")
    print()
    pause_exit(0)

if __name__ == "__main__":
    main()

只需输入c盘的路径,移动到的对应的盘符,YES,即可(我后来保存python为 :migrate把C盘文件移动link到其它盘.py):

image

 

小经验:经过尝试,无法直接重命名:C:\Users\Administrator\AppData\Roaming\Tencent,但是腾讯下面的QQ、WeChat、WXWork这3个都可以改名,可以迁移。


参考文章:win7系统文件夹迁移工具  : https://download.csdn.net/download/vbfgm/8583697

参考文章:神操作!资深IT工程师教你清理C盘90G : https://zhuanlan.zhihu.com/p/720240903
这个文章讲了程序员的Nuget:C:\Users\Administrator\.nuget\packages 占用了我 14.79G内存
具体操作参考:NuGet修改packages目录/迁移缓存文件夹 : https://blog.51cto.com/u_296714/5590171
 
注意经常删除这个临时文件夹:C:\Users\Administrator\AppData\Local\Temp\
安装了钉钉的要特别注意,DingTalkUpdate_ 这个名称开头的文件夹,坚决删掉,,,这个钉钉真的超级变态,没隔多久就自己下载升级文件,升级完了又留下一大堆临时文件,又不删除,占用了我C盘10几G的空间,,你们经常打开钉钉的,估计也占用很多空间
 
posted @ 2024-03-29 11:42  zzgreg  阅读(650)  评论(0)    收藏  举报