You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用C#无需浏览器获取Google Drive视频的流式下载链接?

Hey there! I’ve got you covered on grabbing that streaming download link without firing up Chrome DevTools. Let’s walk through a solid, code-backed approach using C# and the official Google Drive REST API.

Prerequisites First

Before diving into code, let’s get setup sorted:

  • Enable Drive API: Head to the Google Cloud Console, create a project, and enable the Google Drive API.
  • Get Credentials: Create an OAuth 2.0 Client ID (for personal use) or a Service Account (for server-side/automated workflows). Download the JSON credential file (it’ll look like client_secret_xxxx.json).
  • Install NuGet Package: Add the Google.Apis.Drive.v3 package to your C# project—this is the official SDK that wraps the REST API.

Step 1: Authenticate with Google Drive

First, we need to authenticate our app to access Drive files. Here’s a quick OAuth 2.0 example (great for personal use cases):

using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.IO;
using System.Threading;

public class DriveAuthHelper
{
    private static readonly string[] Scopes = { DriveService.Scope.DriveReadonly };
    private const string ApplicationName = "Google Drive Stream Link Grabber";

    public static DriveService GetDriveService()
    {
        UserCredential credential;

        using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
        {
            string credPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), ".credentials/drive-dotnet-streamlink.json");
            credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                GoogleClientSecrets.Load(stream).Secrets,
                Scopes,
                "user",
                CancellationToken.None,
                new FileDataStore(credPath, true)).Result;
            Console.WriteLine("Credential file saved to: " + credPath);
        }

        // Create Drive API service.
        return new DriveService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = ApplicationName,
        });
    }
}

This code handles the OAuth flow—you’ll be prompted to log in to your Google account once, and credentials will be stored locally for future runs.

Now that we have an authenticated DriveService, we can grab the file details and generate a valid streaming link. Let’s break this down:

Extract the File ID

From your example link https://drive.google.com/file/d/0B6zj9fZgMGr7dXl3Z3VxSGRadU0/view, the file ID is 0B6zj9fZgMGr7dXl3Z3VxSGRadU0—we’ll use this to target the file.

Generate the Streaming URL

There are two main scenarios to handle:

1. For Publicly Shared Files (Anyone with Link Can View)

If your video is publicly shared, you can use a direct, unauthenticated streaming link:

public string GetPublicStreamingLink(string fileId)
{
    // This link supports streaming for most video formats (MP4, etc.)
    return $"https://drive.google.com/uc?id={fileId}&export=download";
}

2. For Private Files (Authenticated Access Only)

For private files, we need to use the Drive API’s media endpoint with a valid access token. Here’s how to get that:

public string GetPrivateStreamingLink(DriveService service, string fileId)
{
    // First, verify the file exists and we have access
    var file = service.Files.Get(fileId).Execute();
    if (file == null)
        throw new Exception("File not found or no access permissions");

    // Get the current access token from our authenticated service
    var accessToken = ((UserCredential)service.HttpClientInitializer).Token.AccessToken;

    // Construct the streaming URL with the access token
    return $"https://www.googleapis.com/drive/v3/files/{fileId}?alt=media&access_token={accessToken}";
}

This URL will let you stream the video directly, as long as the access token is valid (OAuth tokens typically expire after 1 hour, but the SDK handles auto-refreshing for you).

Full Example Usage

Putting it all together:

class Program
{
    static void Main(string[] args)
    {
        try
        {
            var driveService = DriveAuthHelper.GetDriveService();
            string fileId = "0B6zj9fZgMGr7dXl3Z3VxSGRadU0"; // Your file ID here

            // Choose the right method based on file privacy
            string streamingLink = GetPrivateStreamingLink(driveService, fileId);
            // OR string streamingLink = GetPublicStreamingLink(fileId);

            Console.WriteLine("Your streaming download link:");
            Console.WriteLine(streamingLink);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }

    // Include the GetPrivateStreamingLink and GetPublicStreamingLink methods here
}

Key Notes to Remember

  • Permissions: Ensure the authenticated Google account has at least read access to the video file. If using a Service Account, you’ll need to manually share the file with the service account’s email address.
  • Streaming Support: Google Drive supports streaming for common video formats like MP4, MOV, and AVI. For less common formats, it might force a direct download instead.
  • Token Expiry: The private streaming link uses a short-lived access token. If you need a long-term solution, consider using a Service Account with domain-wide delegation (if applicable) or implementing token refresh logic.

内容的提问来源于stack exchange,提问作者MinhLee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 04:04:46